Shutil.copy Won't Copy

Nikita Petrov picture Nikita Petrov · Mar 29, 2015 · Viewed 13.2k times · Source

Brand new to programming, diving into it with python and "Learning Python the Hard Way."

For some reason I can not get shutil.copy to copy a file. On my desktop I currently have a file "test1.txt" and another "test2.txt". I want to copy whats in test1 into test2.

In another discussion about how to copy files in the fewest lines possible I found this code:

import shutil, sys  
shutil.copy(sys.argv[a], sys.argv[b]) # <- I plug in test1 and test2

I get the error - NameError: name 'test1' is not defined

However, no variation of putting test1 and test2 into a and b runs successfully. I've tried test, test1.txt, setting the test1 variable and then plugging it in, nothing.

Answer

Vidhya G picture Vidhya G · Mar 29, 2015

sys.argv returns a list. sys.argv[0] contains the name of the script, sys.argv[1] and sys.argv[2] contain the command line arguments:

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

Command line:

$ python filecopy.py t1.txt t2.txt

Output:

['filecopy.py', 't1.txt', 't2.txt'] 

And files t2.txt and text2 have been written. Note that sys.argv[0] might contain the full pathname rather than just the filename (this is OS dependent).