制作文件排序脚本时出错

时间:2016-10-25 04:11:19

标签: python

我正在尝试编写一个对我的下载进行排序的程序;但是,当我尝试运行它时,我得到了这个:

Traceback (most recent call last):
  File "/usr/lib/python3.5/shutil.py", line 538, in move
    os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory:'UntitledDocument.txt' -> 'Downloads/TxtFiles/UntitledDocument.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/nicholas/Python/DownloadSorter.py", line 19, in <module>
    shutil.move(file, folders[fileType])
  File "/usr/lib/python3.5/shutil.py", line 552, in move
    copy_function(src, real_dst)
  File "/usr/lib/python3.5/shutil.py", line 251, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.5/shutil.py", line 114, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'UntitledDocument.txt'

这是代码:     #!的/ usr / bin中/ python3     进口口     import shutil

folders = {
    '.tar.gz': 'Downloads/TarFiles',
    '.deb': 'Downloads/DebFiles',
    '.iso': 'Downloads/IsoFiles',
    '.txt': 'Downloads/TxtFiles',
    '.exe': 'Downloads/ExeFiles',
    '.mp3': 'Videos',
    '.wav': 'Music'
}
os.chdir('/home/nicholas/')

for file in os.listdir('Downloads'):
    for fileType in folders.keys():
        if file.endswith(fileType):
            shutil.move(file, folders[fileType])

1 个答案:

答案 0 :(得分:0)

问题是您使用的文件名没有路径,shutilDownloads目录的工作目录intead中查找该文件。

修复很简单:

shutil.move(os.path.join('Downloads', file), folders[fileType])