python - 重命名具有增量索引的目录中的文件

标签 python filenames prepend

输入:我想在按日期排序的目录中的文件名中添加递增的数字。例如,将“01_”、“02_”、“03_”...添加到下面的这些文件中。

test1.txt (oldest text file)
test2.txt
test3.txt
test4.txt (newest text file)

这是到目前为止的代码。我可以获得文件名,但文件名中的每个字符似乎都是列表中它自己的项目。

import os
for file in os.listdir("/Users/Admin/Documents/Test"):
if file.endswith(".txt"):
      print(file)

预期的结果是:

   01_test1.txt
   02_test2.txt
   03_test3.txt
   04_test4.txt

test1 是最旧的,test 4 是最新的。

如何为每个文件名添加 01_、02_、03_、04_?

我试过这样的事情。但它会为文件名中的每个字符添加一个“01_”。

new_test_names = ['01_'.format(i) for i in file]
print (new_test_names)

最佳答案

  1. 如果您想按年龄对文件进行编号,则需要先对它们进行排序。您调用 sorted 并传递一个 key 参数。 os.path.getmtime 函数将按年龄升序排序(从旧到晚)。

  2. 使用 glob.glob 获取给定目录中的所有 文本文件。目前它不是递归的,但如果您使用的是 python3,递归扩展是一个最小的添加。

  3. 0x_

    形式的字符串使用 str.zfill
  4. 使用os.rename 重命名您的文件

import glob
import os

sorted_files = sorted(
    glob.glob('path/to/your/directory/*.txt'), key=os.path.getmtime)

for i, f in enumerate(sorted_files, 1):
    try:
        head, tail = os.path.split(f)            
        os.rename(f, os.path.join(head, str(i).zfill(2) + '_' + tail))
    except OSError:
        print('Invalid operation')

它总是有助于使用 try-except 进行检查,以捕获任何不应发生的错误。

关于python - 重命名具有增量索引的目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557412/

相关文章:

python - 在 python 中找不到文件作为附件发送

python - 如何在 Python (cuPy/Numpy) 中将行与相应的列相乘?

python - 初学者 Python : save output file as argv input filename

python - 使用python将某些文件从一个文件夹复制到另一个文件夹

javascript - 通过 .htaccess 添加文件以指定标签

python - Pandas groupby 和减去行

excel - 为什么我得到一个不存在的文件名?

bash - 添加到 $PATH 之前

javascript - 为每个 div 添加一个数字

python - 使用 BeautifulSoup 提取时保留某些 HTML 标签