04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 11 ■ FILES AND STUFF 267<br />

>>> third<br />

'This is the third line\n'<br />

■Note The syntax print >> file, text prints the text to the given file object.<br />

In this example, it’s important to note the following:<br />

• I’ve used print to write to the file; this automatically adds newlines after the strings<br />

I supply.<br />

• I use sequence unpacking on the opened file, putting each line in a separate variable.<br />

(This isn’t exactly common practice because you usually won’t know the number of lines<br />

in your file, but it demonstrates the “iteratorness” of the file object.)<br />

• I close the file after having written to it, to ensure that the data is flushed to disk. (As you<br />

can see, I haven’t closed it after reading from it. Sloppy, perhaps, but not critical.)<br />

A Quick Summary<br />

In this chapter, you’ve seen how to interact with the environment through files and file-like<br />

objects, one of the most important techniques for I/O (input/output) in Python. Here are some<br />

of the highlights from the chapter:<br />

File-like objects. A file-like object is (informally) an object that supports a set of methods<br />

such as read and readline (and possibly write and writelines).<br />

Opening and closing files. You open a file with the open function (in newer versions of<br />

Python, actually just an alias for file), by supplying a file name.<br />

Modes and file types. When opening a file, you can also supply a mode, such as 'r' for read<br />

mode or 'w' for write mode. By appending 'b' to your mode, you can open files as binary<br />

files. (This is necessary only on platforms where Python performs line-ending conversion,<br />

such as Windows.)<br />

Standard streams. The three standard files (stdin, stdout, and stderr, found in the sys<br />

module) are file-like objects that implement the UNIX standard I/O mechanism (also<br />

available in Windows).<br />

Reading and writing. You read from a file or file-like object using the method read. You<br />

write with the method write.<br />

Reading and writing lines. You can read lines from a file using readline, readlines, and<br />

(for efficient iteration) xreadlines. You can write files with writelines.<br />

Iterating over file contents. There are many ways of iterating over file contents. It is most<br />

common to iterate over the lines of a text file, and you can do this by simply iterating over<br />

the file itself. There are other methods too, such as readlines and xreadlines, that are<br />

compatible with older versions of Python.

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

Saved successfully!

Ooh no, something went wrong!