python - Shutil.copy 不会复制

标签 python shutil

编程的新手,使用 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.txttext2已经写入。请注意,sys.argv[0] 可能包含完整路径名而不仅仅是文件名(这取决于操作系统)。

关于python - Shutil.copy 不会复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325775/

相关文章:

python - Linux Python 上的操作不允许错误

python - 为什么 os.remove() 或 shutil.move() 只能移动部分文件

python - 在Python中获取每月的工作日数

python - Spark 2.0 DataFrame 初始化可能存在的错误

python - shutil.rmtree() 说明

python - 我可以选择要在shutil 中存档的文件吗?

python - 为什么纹理索引 31 在 Moderngl 中被覆盖?

python - 极其基础的神经网络不学习

python - auto_now 和 auto_now_add 之间的区别

python - 调用函数报错 'not subscriptable'