Shutil.copy Won't Copy

17,532

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

Share:
17,532
Nikita Petrov
Author by

Nikita Petrov

Updated on June 23, 2022

Comments

  • Nikita Petrov
    Nikita Petrov about 2 years

    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.

  • Nikita Petrov
    Nikita Petrov about 9 years
    I tried that as well and could not get it to work. If I plug in "test1" or "test1.txt", etc it gives the same error.
  • Nikita Petrov
    Nikita Petrov about 9 years
    Thank you this worked! Only difference is to do "test1.txt" instead of "test1".
  • Nikita Petrov
    Nikita Petrov about 9 years
    Thank you for the indepth explanation! I totally did not realize that we literally use the numbers in the sys.argv part instead of plugging in our file name.