批量删除文件名中的字符

8 投票
4 回答
27655 浏览
提问于 2025-04-18 10:18

我在Windows资源管理器里有三个主要文件夹,这些文件夹里有一些文件,文件名像这样:ALB_01_00000_intsect_d.kml 或者 Baxters_Creek_AL_intsect_d.kml。虽然第一个名字会变化,但我想从所有这些文件中删除的部分是“_intsect_d”。我想对每个文件夹里的所有文件都这样处理。这些文件的扩展名是.kml。根据上面的例子,我希望得到的结果是 ALB_01_00000.kml 和 Baxters_Creek_AL.kml。我对Python编程不太了解,但希望能得到帮助,写一个脚本来实现上面提到的结果。谢谢。

4 个回答

0
import os
#to get directory path you are in now
os.getcwd()
#you will see you'r not at the same path of your files 
#you must change your path to folder having your files 
os.chdir('''/the_folder_path ''')
#then you will use this 
for filename in os.listdir('''/your_folder_path'''):
    os.rename(filename, filename.replace('what_you_need_to_replace', 'your_change'))

在macOS上这样做是可以的,但我觉得在Windows上你需要在目录路径中使用//。

2

我没有足够的声望来评论nicholas的解决方案,但那段代码会出问题,如果文件夹的名字里有你想替换的字符。

比如说,如果你想用 newname = path.replace('_', '') 来替换下划线,但你的路径是 /path/to/data_dir/control_43.csv,那么你会遇到一个错误:OSError: [Errno 2] No such file or directory,意思是找不到这个文件或目录。

3

这段代码可以用来从一个文件夹里的所有文件名中,递归地删除特定的字符或一组字符,并可以用其他字符、字符组合或者什么都不替换它们。

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)
19

在编程中,有时候我们需要在代码中使用一些特定的块,这些块可以是代码、文本或者其他内容。比如,像

import os
for filename in os.listdir('dirname'):
    os.rename(filename, filename.replace('_intsect_d', ''))
这样的占位符就是用来表示某段代码的地方。它们不会被翻译或删除,而是保留原样,以便在需要的时候可以插入具体的代码。

撰写回答