[英]Problems with shutil.move() and copy()
我在Stackoverflow上阅读了一些关于shutil.move,复制和重命名的文章。 使用这些引用,我似乎仍然无法在使用Python 2.7的Windows 7 Professional环境下执行此脚本而没有错误。
我在这做错了什么?
import shutil
shutil.move('C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')
错误:
没有这样的文件或目录:C:/Data/Download/Somefile.txt.zip
我试过//,\\和其他没有结果的路径。 我在这里错过了什么?
这是我使用的参考脚本:
import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
if files.endswith(".txt"):
shutil.copy(files,destination)
为了更可靠的路径构建,我强烈推荐os.path.join
:
from os.path import join
import shutil
source = join('C', 'Data', 'Download', 'Somefile.txt.zip')
destination = join('C', 'Data', 'Archive')
shutil.move(source, destination)
join
在不同平台之间相对可移植,您可以绕过与斜杠,反斜杠和转义相关的所有痛点。 此外,它允许您将路径视为它们的原样,而不是使用字符串作为路径的代理。
您还可以查看此答案 ,了解更多专业人士。
import shutil
shutil.move(r'C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.