如何在不使用shutil的情况下将文件从一次位置复制到另一个位置
问题描述:
我尝试过使用shutil,但是python调试器正在抛出错误。我可以知道为什么会这样?有没有其他方法?如何在不使用shutil的情况下将文件从一次位置复制到另一个位置
path = "C:\\Program Files (x86)"
if os.path.exists(path):
src= "C:\\Program Files (x86)\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
else:
src= "C:\\Program Files\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
dest = "C:\\Sanity_Automation\\"
shutil.copy(src,dest)
更新:
收到此错误:
Traceback (most recent call last):
File "C:\Sanity_Automation\Work_Project\copy.py", line 15, in <module>
shutil.copy(src, dest)
File "C:\Sanity_Automation\Python272\lib\shutil.py", line 116, in copy
copyfile(src, dst)
File "C:\Sanity_Automation\Python272\lib\shutil.py", line 81, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: 'C:\\Program Files (x86)\\Agilent\\N2X\\QuickTest\\Scripts\\R
答
import os
os.system('mv /src/path /new/path')
或
import os
os.rename('/source/path', '/source/new_path')
有除了shutils你只有两个选择(但两者都没有一个解决方案你的问题)
其次,因为你正在运行Win7的(或64位服务器操作系统),你不跑你的cmd.exe PROMT(或Python脚本)作为管理员您原来的问题是最有可能的。
管理C:\Program Files\
(和(x86))对于普通用户是被禁止的。
尝试将您的脚本放在C:\Users\<your username>\Desktop\quicktest\
而不是看看是否得到相同的错误。或者以管理员身份运行cmd.exe或python脚本。
答
使用shutil
是正确的方式来实现你想要的,所以你应该理解为什么它失败而不是寻找替代品。
您回溯显示:
IOError: [Errno 13] Permission denied: 'C:\\Program Files (x86)\\Agilent\\N2X\\QuickTest\\Scripts\\R
使用其它的复制方法将无法修复权限问题。正如Torxed在他的回答中所述,您很可能在Windows 7下运行Program Files目录受限制的权限。
在一个侧面说明,你应该考虑使用raw strings由前缀文字包含反斜杠路径与r
:
path = r"C:\Program Files (x86)"