如何使用重命名功能



这是我得到的错误:

系统找不到指定的文件:"1.jpg"->"0.jpg"

即使我在目录中也有一个名为 1.jpg 的文件。

我正在制作文件重命名脚本,该脚本重命名目录中的所有文件,每个文件都有一个增加 +1 的数字。

import os
def moving_script():
directory = input("Give the directory")
xlist = os.listdir(directory)
counter = 0
for files in xlist:
    os.rename(files, str(counter)+".jpg")
    counter = counter + 1
moving_script()

它应该重命名所有文件,为"0.jpg"、"1.jpg"等

代码:

import os

def moving_script():
    directory = input("Give the directory")
    xlist = os.listdir(directory)
    counter = 0
    for files in xlist:
        os.rename(os.path.join(directory, files),
                  os.path.join(directory, str(counter)+".jpg"))
        counter = counter + 1

if __name__ == '__main__':
    moving_script()

结果:

~/Documents$ touch file0 file1 file2 file3 file4

ls ~/Documents/
file0  file1  file2  file3  file4

$ python renamer.py
Give the directory'/home/suser/Documents'
$ ls ~/Documents/
0.jpg  1.jpg  2.jpg  3.jpg  4.jpg

os.listdir()将返回文件名,但不包括 path。因此,当您将files传递给os.rename()时,它会在当前工作目录中查找它,而不是它们所在的目录(即由用户提供)。

import os
def moving_script():
    directory = input("Give the directory")
    counter = -1
    for file_name in os.listdir(directory):
        old_name = os.path.join(directory, file_name)
        ext = os.path.splitext(file_name)[-1] # get the file extension
        while True:
            counter += 1
            new_name = os.path.join(directory, '{}{}'.format(counter, ext))
            if not os.path.exists(new_name):
                os.rename(old_name, new_name)
                break
moving_script()

请注意,此代码检测文件扩展名是什么。在您的代码中,您可以使用扩展名重命名.jpg非 jpg 文件。为避免这种情况,您可以将os.listdir(directory)更改为glob.glob(os.path.join(directory, *.jpg')),它将仅迭代"*.jpg"文件。不要忘记您需要导入glob并且在 Linux 上它也区分大小写,因此"*.jpg"不会返回"*"。JPG' 文件

编辑:代码更新以检查新文件名是否已存在。

最新更新