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

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

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


当前回答

你可以使用os。系统函数的简单性和调用bash来完成任务:

import os
os.system('mv old_filename new_filename')

其他回答

使用操作系统。Rename (src, dst)重命名或移动文件或目录。

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo

这是一个基于你最新评论的脚本。

#!/usr/bin/env python
from os import rename, listdir

badprefix = "cheese_"
fnames = listdir('.')

for fname in fnames:
    if fname.startswith(badprefix*2):
        rename(fname, fname.replace(badprefix, '', 1))

试试这个:

import os
import shutil

for file in os.listdir(dirpath):
    newfile = os.path.join(dirpath, file.split("_",1)[1])
    shutil.move(os.path.join(dirpath,file),newfile)

我假设您不想删除文件扩展名,但您可以对句号进行相同的分割。

这个命令将使用重命名器从当前目录下的所有文件中删除初始的"CHEESE_"字符串:

$ renamer --find "/^CHEESE_/" *

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

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

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)