gpt4 book ai didi

python - 如何重命名文件以包含文件路径?

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:20 24 4
gpt4 key购买 nike

现在,我的考试文件是这样排序的:

enter image description here

其中 y 代表年份,s 代表主题。每个主题文件夹中有 3 个文件 - t1.txt、t2.txt 和 t3.txt,代表当年该主题的 3 个不同测试。

我试图将所有主题放在一个文件夹中,这需要将年份添加到文件名的开头,否则将有 9 个同名文件。

到目前为止我的代码是:

import os

mypath = 'D:\\Queensland Academies\\IB Resources\\test'

for root, subdir, file in os.walk(mypath):
for f in file:
new = 'test' + f
print(new)
os.rename(os.path.join(mypath, f), os.path.join(mypath, new))

然而,这会返回:FileNotFoundError: [WinError 2] The system cannot find the file specified

我做错了什么?

编辑:我目前的目标不是移动任何文件,而是简单地重命名它们

最佳答案

import os

mypath = 'D:\\Queensland Academies\\IB Resources\\test'

for root, subdir, file in os.walk(mypath):
for f in file:
dirs = root.split("\\") [1:] # omit drive letter
new = '_'.join(dirs) + '_' + f

# print(new)
os.rename(os.path.join(root, f), os.path.join(root, new))

从 subdir 中获取目录名称,省略驱动器号并将它们与 '_' 和原始文件名组合....

'mypath' 只是 os.walk() 的起始路径 - 它不是当前手头文件所在的位置。


如果我使用这段代码(将 os.rename 替换为 print),我会得到我的 C:\temp\:

c:\temp\a;b.txt           c:\temp\temp_a;b.txt
c:\temp\new 1.txt c:\temp\temp_new 1.txt
c:\temp\new 2.txt c:\temp\temp_new 2.txt
c:\temp\numbers.dat.txt c:\temp\temp_numbers.dat.txt
c:\temp\tempfile.txt c:\temp\temp_tempfile.txt
c:\temp\tempfile.txt.gz c:\temp\temp_tempfile.txt.gz
c:\temp\tempfile.txt.gzip c:\temp\temp_tempfile.txt.gzip

关于python - 如何重命名文件以包含文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com