Sta*_*cyM 2 python filenames prepend
输入:我想在按日期排序的目录中的文件名中增加数字。例如,将“ 01 _”,“ 02 _”,“ 03 _” ...添加到下面的这些文件中。
test1.txt (oldest text file)
test2.txt
test3.txt
test4.txt (newest text file)
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是代码。我可以获取文件名,但是文件名中的每个字符似乎都是列表中自己的项。
import os
for file in os.listdir("/Users/Admin/Documents/Test"):
if file.endswith(".txt"):
print(file)
Run Code Online (Sandbox Code Playgroud)
预期的结果是:
01_test1.txt
02_test2.txt
03_test3.txt
04_test4.txt
Run Code Online (Sandbox Code Playgroud)
test1是最旧的,而test 4是最新的。
如何在每个文件名中添加01_,02_,03_,04_?
我已经尝试过这样的事情。但是它会在文件名中的每个单个字符上添加一个“ 01_”。
new_test_names = ['01_'.format(i) for i in file]
print (new_test_names)
Run Code Online (Sandbox Code Playgroud)
如果要按年龄对文件编号,则需要先对其进行排序。您调用sorted并传递一个key参数。该功能os.path.getmtime将按照年龄从大到小的顺序进行排序。
使用glob.glob让所有在给定的目录中的文本文件。到目前为止,它不是递归的,但是如果您使用的是python3,则递归扩展是最少的添加。
用于str.zfill形式的字符串0x_
用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')
Run Code Online (Sandbox Code Playgroud)
使用总是可以帮助进行检查try-except,以捕获不应该发生的任何错误。