与os.rename()函数斗争

时间:2018-06-05 17:39:55

标签: python

我试图删除python 3中下载文件夹中每个文件的下划线但我的程序最终出现错误

到目前为止,这是我的代码:

import shutil, os, re
for folder, downloads, songs in os.walk("C:/Users/TheTrojanHorse/Downloads"):
    print("the current folder is",folder)
    for song in songs:
        temp = song
        temp = (re.sub('[_]', ' ',temp))
        os.rename(song,temp)

这是错误:

os.rename(song,temp)
FileNotFoundError: [WinError 2] The system cannot find the file specified

1 个答案:

答案 0 :(得分:1)

您需要指定song的完整路径(可能temp),否则操作系统将在当前目录中而不是C:/Users/TheTrojanHorse/Downloads中查找该文件:

os.rename(os.path.join(folder, song), os.path.join(folder, temp))