为文件名添加编号

卡尔格

我是 Python 新手。我有一个包含数百个文件的目录。我想在每个文件的开头添加一个累进数字,例如:001_filename 等等......我想使用三位数字进行编号。感谢那些可以帮助我的人!

蘑菇机

以下 Python 脚本重命名给定目录中的所有文件。

解释

它首先检查提供的路径是否实际上是一个目录以及它是否存在。如果不是,它会打印一条错误消息并以非零退出代码离开程序。

否则,它将检索该目录中的所有文件名并根据文件的最后修改日期对文件进行排序。key=您可以通过为 的参数提供另一个 lambda 函数来轻松调整排序标准sorted()这实际上不是必需的,但是按照os.listdir()您的文件系统确定的顺序获取结果,这是确保根据您指定的标准重命名的唯一方法。

之后,它确定使用唯一 ID 唯一标识每个文件所需的位数。即使目录中有数百个文件(如您的情况),这也将确保脚本正常工作。为了在使用时坚持您的问题,max()我确保它始终至少为三位数,即使它们不需要唯一标识文件。
如果有必要,它最终会重命名文件,即文件还没有所需的文件名。

脚本

import os
import sys

dir = "mydir"
if not (os.path.exists(dir) and os.path.isdir(dir)):
    # write error message to stderr
    print(f"Directory {dir} does not not exist or is not a directory.", file=sys.stderr)
    # exit program with exit code 1 indicating the script has failed
    sys.exit(1)
# get all files in the directory and store for each file it's name and the full path to the file
# This way we won't have to create the full path many times
my_files = [(file, os.path.join(dir, file)) for file in os.listdir(dir) if os.path.isfile(os.path.join(dir, file))]
# sort by "modified" timestamp in reverse order => file with most recent modified date first
# we need to use the fullpath here which is the second element in the tuple
sorted_by_creation_date = sorted(my_files, key=lambda file: os.path.getmtime(file[1]), reverse=True)
# get number of digits required to assign a unique value
number_of_digits = len(str(len(my_files)))
# use at least 3 digits, even if that's not actually required to uniquely assign values
number_of_digits = max(3, number_of_digits)

# loop over all files and rename them
print("Renaming files...")
for index, (file, fullpath) in enumerate(my_files):
    # rename files with leading zeros and start with index 1 instead of 0
    new_filename = f"file{index + 1}.txt"#f"{index + 1:0{number_of_digits}d}_{file}" #f"file{index + 1}.txt"
    if new_filename == file:
        # move on to next file if the file already has the desired filename
        print(f"File already has the desired filename {file}. Skipping file.")
        continue
    # concatenate new filename with path to directory
    new_name = os.path.join(dir, new_filename)
    # rename the file
    print(f"{file} => {new_filename}")
    os.rename(fullpath, new_name)

print("Done.")

如果您想在某个目录中运行脚本python myscript.py并重命名该目录中的文件,您可以使用它dir = os.getcwd()来获取脚本中的当前工作目录,而不是像上面的脚本(dir = "mydir")那样硬编码目录。

此实现不会重命名嵌套目录中的文件,但如果需要,您可以调整程序以执行此操作。在这种情况下,可能想看看os.walk()

例子

像这样的目录示例:

注意:这使用上面的脚本和硬编码的目录名称mydir

mydir/
├── file1.txt
├── file2.txt
├── file3.txt
└── Test
    └── test.txt

运行脚本

python myscript.py

脚本输出

Renaming files...
file1.txt => 001_file1.txt
file2.txt => 002_file2.txt
file3.txt => 003_file3.txt
Done.

结果

mydir/
├── 001_file1.txt
├── 002_file2.txt
├── 003_file3.txt
└── Test
    └── test.txt

如您所见,文件按预期重命名,嵌套目录保持不变。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章