2014-06-19 42 views
1

我在Windows资源管理器中有3个主文件夹,其中包含名为ALB_01_00000_intsect_d.kml或Baxters_Creek_AL_intsect_d.kml的文件。尽管名字改变了我想要从所有这些文件中删除的一致性,但是“_intsect_d”。希望为每个文件夹中的所有文件执行此操作。这些文件的扩展名为.kml。根据上面的例子,我期待的结果是ALB_01_00000.kml,另一个是 Baxters_Creek_AL.kml。不太了解Python的编程知识,但希望能帮助编写一个可以实现上述结果的脚本。由于从批处理文件中删除字符

+0

请仔细阅读这个问题 - 这可能是有用的:http://stackoverflow.com/questions/24297468/removing-字符,从文件名,在批 –

回答

4
import os 
for filename in os.listdir('dirname'): 
    os.rename(filename, filename.replace('_intsect_d', '')) 
0

该代码可用于一个目录中删除任何特定的字符或所有文件名字符集的递归与其他任何字符,字符集或没有字符替换它们。

import os 

paths = (os.path.join(root, filename) 
     for root, _, filenames in os.walk('C:\FolderName') 
     for filename in filenames) 

for path in paths: 
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory 
    newname = path.replace('#', '-') 
    if newname != path: 
     os.rename(path, newname) 
0

我没有足够的声望来评论尼古拉斯的解决方案,但是如果任何文件夹名称包含您要替换的字符,则代码会中断。

举例来说,如果你想newname = path.replace('_', '')但你的路径看起来像/path/to/data_dir/control_43.csv你会得到一个OSError: [Errno 2] No such file or directory