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

时间:2018-06-10 06:44:35

标签: python

现在,我的考试文件是这样订购的:

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

我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

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))

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

'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