编程的新手,使用 Python 和“艰难地学习 Python”深入研究它。
出于某种原因,我无法使用 shutil.copy
来复制文件。在我的桌面上,我目前有一个文件“test1.txt”和另一个“test2.txt”。我想将 test1 中的内容复制到 test2 中。
在另一个关于如何以尽可能少的行复制文件的讨论中,我找到了这段代码:
import shutil, sys
shutil.copy(sys.argv[a], sys.argv[b]) # <- I plug in test1 and test2
我收到错误 - NameError: name 'test1' is not defined
但是,将 test1 和 test2 放入 a 和 b 的变体没有成功运行。我已经尝试过测试,test1.txt,设置 test1 变量,然后将其插入,什么都没有。
最佳答案
sys.argv
返回一个列表。 sys.argv[0]
包含脚本的名称,sys.argv[1]
和 sys.argv[2]
包含命令行参数:
import shutil, sys
print sys.argv # print out the list so you can see what it looks like
a = sys.argv[1]
b = sys.argv[2]
shutil.copy(a, b) # a & b take their values from the command line
shutil.copy('text1','text2') # here shutil is using hard coded names
命令行:
$ python filecopy.py t1.txt t2.txt
输出:
['filecopy.py', 't1.txt', 't2.txt']
并且文件t2.txt
和text2
已经写入。请注意,sys.argv[0]
可能包含完整路径名而不仅仅是文件名(这取决于操作系统)。
关于python - Shutil.copy 不会复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325775/