15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.6. First <strong>Python</strong> Programs<br />

Now that we are familiar with the syntax, style, variable assignment, and memory allocation, it is time<br />

to look at slightly more complex code. You may or may not be familiar with all of the constructs of<br />

<strong>Python</strong> that we're going to show, but we believe that <strong>Python</strong> is so simple and elegant that you should be<br />

able to figure out what each piece of code does.<br />

We are going to introduce two related scripts that manipulate text files. The first, makeTextFile.py,<br />

creates text files. It prompts the user for each line of text and writes the results to a file. The other,<br />

readTextFile.py, reads and displays the contents of a text file to the screen.<br />

Take a look at both now, and see if you can figure out how each works.<br />

Example 3.1. File Create (makeTextFile.py)<br />

This application prompts the user for a (nonexistent) filename, then has the user enter<br />

each line of that file (one at a time). Finally, it writes the entire text file to disk.<br />

1 #!/usr/bin/env python<br />

2<br />

3 'makeTextFile.py -- create text file'<br />

4<br />

5 import os<br />

6 ls = os.linesep<br />

7<br />

8 # get filename<br />

9 while True:<br />

10<br />

11 if os.path.exists(fname):<br />

12 print "ERROR: '%s' already exists" % fname<br />

13 else:<br />

14 break<br />

15<br />

16 # get file content (text) lines<br />

17 all = []<br />

18 print "\nEnter lines ('.' by itself to quit).\n"<br />

19<br />

20 # loop until user terminates input<br />

21 while True:<br />

22 entry = raw_input('> ')<br />

23 if entry == '.':<br />

24 break<br />

25 else:<br />

26 all.append(entry)<br />

27<br />

28 # write lines to file with proper line-ending<br />

29 fobj = open(fname, 'w')<br />

30 fobj.writelines(['%s%s' % (x, ls) for x in all])<br />

31 fobj.close()<br />

32 print 'DONE!'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!