Exercise 17. More Files

Now let’s do a few more things with files. We’ll write a Python script to copy one file to another. It’ll be very short but will give you ideas about other things you can do with files.

ex17.py


 1    from sys import argv
 2    from os.path import exists
 3
 4    script, from_file, to_file = argv
 5
 6    print(f"Copying from {from_file} to {to_file}")
 7
 8    # we could do these two on one line, how?
 9    in_file = open(from_file)
10    indata = in_file.read()
11
12    print(f"The input file is {len(indata)} bytes long")
13
14    print(f"Does the output file exist? {exists(to_file)}")
15    print("Ready, hit RETURN to continue, CTRL-C to abort.")
16    input()
17
18    out_file = open(to_file, 'w')
19    out_file.write(indata)
20
21    print("Alright, all done.")
22
23    out_file.close()
24    in_file.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.

What You Should See

Just like your other scripts, run this one with two arguments: the file to copy from and the file to copy it to. I’m going to use a simple test file named test.txt:

Exercise 17 Session


$ # first make a sample file
$ echo "This is a test file." > test.txt
$ # then look at it
$ cat test.txt
This is a test file.
$ # now run our script on it
$ python3.6 ex17.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The input file is 21 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.

Alright, all done.

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 the trick I did with echo to make a file and cat to show the file? You can learn how to do that in the Appendix, “Command Line Crash Course.”


Study Drills

1. This script is really annoying. There’s no need to ask you before doing the copy, and it prints too much out to the screen. Try to make the script more friendly to use by removing features.

2. See how short you can make the script. I could make this one line long.

3. Notice at the end of the What You Should See section I used something called cat? It’s an old command that concatenates files together, but mostly it’s just an easy way to print a file to the screen. Type man cat to read about it.

4. Find out why you had to write out_file.close() in the code.

5. Go read up on Python’s import statement, and start python3.6 to try it out. Try importing some things and see if you can get it right. It’s alright if you do not.

Common Student Questions

Why is the 'w' in quotes? That’s a string. You’ve been using strings for a while now. Make sure you know what a string is.

No way you can make this one line! That ; depends ; on ; how ; you ; define ; one ; line ; of ; code.

Is it normal to feel like this exercise was really hard? Yes, it is totally normal. Programming may not “click” for you until maybe even Exercise 36, or it might not until you finish the book and then make something with Python. Everyone is different, so just keep going and keep reviewing exercises that you had trouble with until it clicks. Be patient.

What does the len() function do? It gets the length of the string that you pass to it then returns that as a number. Play with it.

When I try to make this script shorter I get an error when I close the files at the end. You probably did something like indata = open(from_file).read(), which means you don’t need to then do in_file.close() when you reach the end of the script. It should already be closed by Python once that one line runs.

I get a Syntax:EOL while scanning string literal error. You forgot to end a string properly with a quote. Go look at that line again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.126.80