Nikita Petrov
Nikita Petrov

Reputation: 51

Shutil.copy Won't Copy

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.

Upvotes: 3

Views: 25357

Answers (2)

Vidhya G
Vidhya G

Reputation: 2330

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).

Upvotes: 2

Dan D.
Dan D.

Reputation: 74675

You should use shutil.copy(a, b) and not shutil.copy(sys.argv[a], sys.argv[b]). As evidently the values of a and b are strings presumably path names and not numbers as one would expect if they were meant to be indexes of the sys.argv list.

The following should work if a file or directory named test1 exists:

a = "test1"
b = "test2"
shutil.copy(a, b)

Upvotes: 0

Related Questions