在 python 中连接一个字符串
Concat a String in python
这是我的文件
2015125_0r89_PEO.txt
2015125_0r89_PED.txt
2015125_0r89_PEN.txt
2015126_0r89_PEO.txt
2015126_0r89_PED.txt
2015126_0r89_PEN.txt
2015127_0r89_PEO.txt
2015127_0r89_PED.txt
2015127_0r89_PEN.txt
我想改成这样:
US.CAR.PEO.D.2015.125.txt
US.CAR.PED.D.2015.125.txt
US.CAR.PEN.D.2015.125.txt
US.CAR.PEO.D.2015.126.txt
US.CAR.PED.D.2015.126.txt
US.CAR.PEN.D.2015.126.txt
US.CAR.PEO.D.2015.127.txt
US.CAR.PED.D.2015.127.txt
US.CAR.PEN.D.2015.127.txt
到目前为止,这是我的代码,
import os
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk('C:\data\MAX\') #location files
for filename in filenames)
for path in paths:
a = path.split("_")
b = a[2].split(".")
c = "US.CAR."+ b[0] + ".D." + a[0]
print c
当我 运行 脚本时它不会出错,但不会更改文件的名称 .txt 这是它应该做的
有什么帮助吗?
首先获取路径然后对其进行操作的方式会得到不好的结果,在这种情况下最好先获取文件名,对其进行更改,然后再更改文件名本身,像这样
for root,_,filenames in os.walk('C:\data\MAX\'):
for name in filenames:
print "original:", name
a = name.split("_")
b = a[2].split(".")
new = "US.CAR.{}.D.{}.{}".format(b[0],a[0],b[1]) #don't forget the file extention
print "new",new
os.rename( os.path.join(root,name), os.path.join(root,new) )
字符串拼接效率较低,最好的方法是使用字符串formating.
这是我的文件
2015125_0r89_PEO.txt
2015125_0r89_PED.txt
2015125_0r89_PEN.txt
2015126_0r89_PEO.txt
2015126_0r89_PED.txt
2015126_0r89_PEN.txt
2015127_0r89_PEO.txt
2015127_0r89_PED.txt
2015127_0r89_PEN.txt
我想改成这样:
US.CAR.PEO.D.2015.125.txt
US.CAR.PED.D.2015.125.txt
US.CAR.PEN.D.2015.125.txt
US.CAR.PEO.D.2015.126.txt
US.CAR.PED.D.2015.126.txt
US.CAR.PEN.D.2015.126.txt
US.CAR.PEO.D.2015.127.txt
US.CAR.PED.D.2015.127.txt
US.CAR.PEN.D.2015.127.txt
到目前为止,这是我的代码,
import os
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk('C:\data\MAX\') #location files
for filename in filenames)
for path in paths:
a = path.split("_")
b = a[2].split(".")
c = "US.CAR."+ b[0] + ".D." + a[0]
print c
当我 运行 脚本时它不会出错,但不会更改文件的名称 .txt 这是它应该做的
有什么帮助吗?
首先获取路径然后对其进行操作的方式会得到不好的结果,在这种情况下最好先获取文件名,对其进行更改,然后再更改文件名本身,像这样
for root,_,filenames in os.walk('C:\data\MAX\'):
for name in filenames:
print "original:", name
a = name.split("_")
b = a[2].split(".")
new = "US.CAR.{}.D.{}.{}".format(b[0],a[0],b[1]) #don't forget the file extention
print "new",new
os.rename( os.path.join(root,name), os.path.join(root,new) )
字符串拼接效率较低,最好的方法是使用字符串formating.