Concat在python中的一个字符串

时间:2016-02-03 18:24:18

标签: python-2.7 split concat

这是我的文件

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 它应该做什么

任何帮助?

1 个答案:

答案 0 :(得分:0)

通过首先获取路径然后操作它来实现它会得到不好的结果,在这种情况下最好首先获取文件的名称,对其进行更改然后更改文件本身的名称,像这样

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