我试图用Python重命名目录中的一些文件。

假设我有一个名为CHEESE_CHEESE_TYPE的文件。***,并希望删除CHEESE_,因此我的结果文件名将是CHEESE_TYPE

我正在尝试使用os.path.split,但它不能正常工作。我也考虑过使用字符串操作,但也没有成功。


当前回答

假设您已经在目录中,并且注释中的“前8个字符”始终为真。(虽然“CHEESE_”是7个字符…? 如果是,将下面的8改为7)

from glob import glob
from os import rename
for fname in glob('*.prj'):
    rename(fname, fname[8:])

其他回答

我有同样的问题,我想在任何pdf文件替换空白到破折号。 但这些文件在多个子目录中。因此,我必须使用os。walk()。 在多个子目录的情况下,它可能是这样的:

import os
for dpath, dnames, fnames in os.walk('/path/to/directory'):
    for f in fnames:
        os.chdir(dpath)
        if f.startswith('cheese_'):
            os.rename(f, f.replace('cheese_', ''))

那么这个呢:

import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***

假设您已经在目录中,并且注释中的“前8个字符”始终为真。(虽然“CHEESE_”是7个字符…? 如果是,将下面的8改为7)

from glob import glob
from os import rename
for fname in glob('*.prj'):
    rename(fname, fname[8:])

进口操作系统 进口的字符串 def rename_files ():

#List all files in the directory
file_list = os.listdir("/Users/tedfuller/Desktop/prank/")
print(file_list)

#Change current working directory and print out it's location
working_location = os.chdir("/Users/tedfuller/Desktop/prank/")
working_location = os.getcwd()
print(working_location)

#Rename all the files in that directory
for file_name in file_list:
    os.rename(file_name, file_name.translate(str.maketrans("","",string.digits)))

rename_files ()

下面是一个更普遍的解决方案:

此代码可用于从目录内的所有文件名中递归删除任何特定字符或字符集,并将其替换为任何其他字符、字符集或无字符。

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)