Now let's do a few more things with files. We're going to actually write a Python script to copy one file to another. It'll be very short but will give you some ideas about other things you can do with files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
|
You should immediately notice that we import another handy command named exists. This returns True if a file exists, based on its name in a string as an argument. It returns False if not. We'll be using this function in the second half of this book to do lots of things, but right now you should see how you can import it.
Using import is a way to get tons of free code other better (well, usually) programmers have written so you do not have to write it.
Just like your other scripts, run this one with two arguments, the file to copy from and the file to copy it to. If we use your test.txt file from before we get this:
$ python ex17.py test.txt copied.txt
Copying from test.txt to copied.txt
The input file is 81 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.
$ cat copied.txt
To all the people out there.
I say I don't like my hair.
I need to shave it off.
$
It should work with any file. Try a bunch more and see what happens. Just be careful you do not blast an important file.
Warning
Did you see that trick I did with cat? It only works on Linux or OSX, on Windows use type to do the same thing.