Product SiteDocumentation Site

10.5. copyfile.py

In this example we will copy a given text file to another file.
#!/usr/bin/env python
import sys
if len(sys.argv) < 3:
    print "Wrong parameter"
    print "./copyfile.py file1 file2"
    sys.exit(1)
f1 = open(sys.argv[1])
s = f1.read()
f1.close()
f2 = open(sys.argv[2], 'w')
f2.write(s)
f2.close()

Note

This way of reading file is not always a good idea, a file can be very large to read and fit in the memory. It is always better to read a known size of the file and wirte that to the new file.

You can see we used a new module here sys. sys.argv contains all command line parameters. Remember cp command in shell, after cp we type first the file to be copied and then the new file name.

The first value in sys.argv is the name of the command itself.
#!/usr/bin/env python
import sys
print "First value", sys.argv[0]
print "All values"
for i, x  in enumerate(sys.argv):
    print i, x

The output
$ ./argvtest.py Hi there
First value ./argvtest.py
All values
0 ./argvtest.py
1 Hi
2 there

Here we used a new function enumerate(iterableobject), which returns the index number and the value from the iterable object.