You are here: Home Dive Into Python 3

Difficulty level: ♦♦♦♢♢

Files

FIXME
— FIXME

 

Diving In

FIXME

Reading From Text Files

FIXME

open(..., encoding='...')
open(..., 'r', encoding='...')

Character Encoding Rears Its Ugly Head

FIXME

File Objects

FIXME

Python has a built-in function, open(), for opening a file on disk. The open() function returns a file object, which has methods and attributes for getting information about and manipulating the file.

Reading Data From A Text File

FIXME

6.2.2. Closing Files

Open files consume system resources, and depending on the file mode, other programs may not be able to access them. It’s important to close files as soon as you’re finished with them.

FIXME checking if a file is closed

Using The with Statement

FIXME "with open(...) as file" pattern

Reading Data One Line At A Time

FIXME

FIXME what's a "line"? (line endings discussion, universal line endings, etc.)

Writing to Text Files

FIXME

Character Encoding Again

FIXME

Write A Little, Write A Lot

FIXME write(), writelines(), .writeable

Handling I/O Errors

FIXME

Binary Files

FIXME

>>> image = open('examples/beauregard-100x100.jpg', 'rb')
>>> image
<io.BufferedReader object at 0x00C7A390>
>>> image.mode
'rb'
>>> image.name
'examples/beauregard-100x100.jpg'
>>> image
<io.BufferedReader object at 0x00C7A390>
>>> image.tell()
0
>>> data = image.read(3)
>>> data
b'\xff\xd8\xff'
>>> image.tell()
3
>>> image.seek(0)
0
>>> data = image.read()
>>> len(data)
3150

File-like Objects

FIXME

Standard Input, Output, and Error

FIXME

Further Reading

FIXME

© 2001–9 Mark Pilgrim