Text
stringlengths
1
9.41k
In both Python 3.0 and 2.6, file type is determined by the second argument to open, the mode string—an included “b” means binary.
Python has always supported both text and binary files, but in Python 3.0 there is a sharper distinction between the two: - Text files represent content as normal str strings, perform Unicode encoding and decoding automatically, and perform end-of-line translation by default. - Binary files represent content as a s...
All strings are technically Unicode in 3.0, but ASCII users will not generally notice.
In fact, files and strings work the same in 3.0 and 2.6 if your script’s scope is limited to such simple forms of text. **|** ----- If you need to handle internationalized applications or byte-oriented data, though, the distinction in 3.0 impacts your code (usually for the better).
In general, you must use ``` bytes strings for binary files, and normal str strings for text files.
Moreover, because ``` text files implement Unicode encodings, you cannot open a binary data file in text mode—decoding its content to Unicode text will likely fail. Let’s look at an example.
When you read a binary data file you get back a bytes object— a sequence of small integers that represent absolute byte values (which may or may not correspond to characters), which looks and feels almost exactly like a normal string: `>>> data = open('data.bin', 'rb').read()` _# Open binary file: rb=read binary_ `>>>...
Since Unicode and binary data is of marginal interest to many Python programmers, we’ll postpone the full story until Chapter 36.
For now, let’s move on to some more substantial file examples. ###### Storing and parsing Python objects in files Our next example writes a variety of Python objects into a text file on multiple lines. Notice that it must convert objects to strings using conversion tools.
Again, file data is always strings in our scripts, and write methods do not do any automatic to-string formatting for us (for space, I’m omitting byte-count return values from write methods from here on): `>>> X, Y, Z = 43, 44, 45` _# Native Python objects_ `>>> S = 'Spam'` _# Must be strings to store in file_ ``` >...
Notice that the interactive echo gives the exact byte contents, while the print operation interprets embedded end-of-line characters to render a more user-friendly display: `>>> chars = open('datafile.txt').read()` _# Raw string display_ ``` >>> chars ``` **|** ----- ``` "Spam\n43,44,45\n[1, 2, 3]${'a': 1, 'b'...
As Python never converts strings to numbers (or other types of objects) automatically, this is required if we need to gain access to normal object tools like indexing, addition, and so on: `>>> F = open('datafile.txt')` _# Open again_ `>>> line = F.readline()` _# Read one line_ ``` >>> line 'Spam\n' ``` `>>> line...
Now let’s grab the next line, which contains numbers, and parse out (that is, extract) the objects on that line: `>>> line = F.readline()` _# Next line from file_ `>>> line` _# It's a string here_ ``` '43,44,45\n' ``` `>>> parts = line.split(',')` _# Split (parse) on commas_ ``` >>> parts ['43', '44', '45\n'] ...
We still must convert from strings to integers, though, if we wish to perform math on these: `>>> int(parts[1])` _# Convert from string to int_ ``` 44 ``` `>>> numbers = [int(P) for P in parts]` _# Convert all in list at once_ ``` >>> numbers [43, 44, 45] ``` As we have learned, int translates a string of digi...
Notice that we didn’t have to run rstrip to delete the \n at the end of the last part; int and some other converters quietly ignore whitespace around digits. Finally, to convert the stored list and dictionary in the third line of the file, we can run them through eval, a built-in function that treats a string as a pie...
In fact, sometimes it’s too powerful. eval will happily run any Python expression—even one that might delete all the files on your computer, given the necessary permissions!
If you really want to store native Python objects, but you can’t trust the source of the data in the file, Python’s standard library pickle module is ideal. The pickle module is an advanced tool that allows us to store almost any Python object in a file directly, with no to- or from-string conversion requirement on ou...
It’s like a super-general data formatting and parsing utility.
To store a dictionary in a file, for instance, we pickle it directly: ``` >>> D = {'a': 1, 'b': 2} >>> F = open('datafile.pkl', 'wb') >>> import pickle ``` `>>> pickle.dump(D, F)` _# Pickle any object to file_ ``` >>> F.close() ``` Then, to get the dictionary back later, we simply use pickle again to re-creat...
The pickle module performs what is known as object serialization—converting objects to and from strings of bytes—but requires very little work on our part.
In fact, pickle internally translates our dictionary to a string form, though it’s not much to look at (and may vary if we pickle in other data protocol modes): `>>> open('datafile.pkl', 'rb').read()` _# Format is prone to change!_ ``` b'\x80\x03}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.' ```...
For more on the pickle module, see the Python standard library manual, or import pickle and pass it to help interactively. While you’re exploring, also take a look at the shelve module.
shelve is a tool that uses pickle to store Python objects in an access-by-key filesystem, which is beyond our scope here (though you will get to see **|** ----- an example of shelve in action in Chapter 27, and other pickle examples in Chapters 30 and 36). Note that I opened the file used to store the pickled obje...
In earlier Pythons it’s OK to use text-mode files for protocol 0 (the default, which creates ASCII text), as long as text mode is used consistently; higher protocols require binary-mode files.
Python 3.0’s default protocol is 3 (binary), but it creates bytes even for protocol 0.
See Chapter 36, Python’s library manual, or reference books for more details on this. Python 2.6 also has a cPickle module, which is an optimized version of ``` pickle that can be imported directly for speed.
Python 3.0 renames this ``` module _pickle and uses it automatically in pickle—scripts simply import pickle and let Python optimize itself. ###### Storing and parsing packed binary data in files One other file-related note before we move on: some advanced applications also need to deal with packed binary data, creat...
Python’s standard library includes a tool to help in this domain—the struct module knows how to both compose and parse packed binary data.
In a sense, this is another dataconversion tool that interprets strings in files as binary data. To create a packed binary data file, for example, open it in 'wb' (write binary) mode, and pass struct a format string and some Python objects.
The format string used here means pack as a 4-byte integer, a 4-character string, and a 2-byte integer, all in bigendian form (other format codes handle padding bytes, floating-point numbers, and more): `>>> F = open('data.bin', 'wb')` _# Open binary output file_ ``` >>> import struct ``` `>>> data = struct.pack('>...
To parse the values out to normal Python objects, we simply read the string back and unpack it using the same format string.
Python extracts the values into normal Python objects—integers and a string: ``` >>> F = open('data.bin', 'rb') ``` `>>> data = F.read()` _# Get packed binary data_ ``` >>> data b'\x00\x00\x00\x07spam\x00\x08' ``` **|** ----- `>>> values = struct.unpack('>i4sh', data)` _# Convert to Python objects_ ``` >>>...
Also note that the binary file-processing modes 'wb' and 'rb' can be used to process a simpler binary file such as an image or audio file as a whole without having to unpack its contents. ###### File context managers You’ll also want to watch for Chapter 33’s discussion of the file’s _context manager_ support, new in...
Though more a feature of exception processing than files themselves, it allows us to wrap file-processing code in a logic layer that ensures that the file will be closed automatically on exit, instead of relying on the autoclose on garbage collection: ``` with open(r'C:\misc\data.txt') as myfile: # See Chapter 33 ...
For instance, as mentioned earlier, seek resets your current position in a file (the next read or write happens at that position), flush forces buffered output to be written out to disk (by default, files are always buffered), and so on. The Python standard library manual and the reference books described in the Prefa...
For more file-processing examples, watch for the sidebar “Why You Will Care: File Scanners” on page 340.
It sketches common file-scanning loop code patterns with statements we have not covered enough yet to use here. **|** ----- Also, note that although the open function and the file objects it returns are your main interface to external files in a Python script, there are additional file-like tools in the Python tool...
Also available, to name a few, are: _Standard streams_ Preopened file objects in the sys module, such as sys.stdout (see “Print Operations” on page 297) _Descriptor files in the os module_ Integer file handles that support lower-level tools such as file locking _Sockets, pipes, and FIFOs_ File-like objects used to syn...
See more advanced Python texts and the Web at large for additional information on file-like tools. _Version skew note: In Python 2.5 and earlier, the built-in name open is_ essentially a synonym for the name file, and files may technically be opened by calling either open or file (though open is generally preferred fo...
In Python 3.0, the name file is no longer available, because of its redundancy with open. Python 2.6 users may also use the name file as the file object type, in order to customize files with object-oriented programming (described later in this book).
In Python 3.0, files have changed radically. The classes used to implement file objects live in the standard library module ``` io.
See this module’s documentation or code for the classes it makes ``` available for customization, and run a type(F) call on open files F for hints. ###### Type Categories Revisited Now that we’ve seen all of Python’s core built-in types in action, let’s wrap up our object types tour by reviewing some of the properti...
Table 9-3 classifies all the major types we’ve seen so far according to the type categories introduced earlier. Here are some points to remember: **|** ----- - Objects share operations according to their category; for instance, strings, lists, and tuples all share sequence operations such as concatenation, length,...
Object classifications_ **Object type** **Category** **Mutable?** Numbers (all) Numeric No Strings Sequence No Lists Sequence Yes Dictionaries Mapping Yes Tuples Sequence No Files Extension N/A Sets Set Yes `frozenset` Set No `bytearray (3.0)` Sequence Yes In Part VI ``` class MySequence: def __ge...
In general: - Lists, dictionaries, and tuples can hold any kind of object. - Lists, dictionaries, and tuples can be arbitrarily nested. - Lists and dictionaries can dynamically grow and shrink. Because they support arbitrary structures, Python’s compound object types are good at representing complex information ...
For example, values in dictionaries may be lists, which may contain tuples, which may contain dictionaries, and so on.
The nesting can be as deep as needed to model the data to be processed. Let’s look at an example of nesting.
The following interaction defines a tree of nested compound sequence objects, shown in Figure 9-1. To access its components, you may include as many index operations as required.
Python evaluates the indexes from left to right, and fetches a reference to a more deeply nested object at each step.
Figure 9-1 may be a pathologically complicated data structure, but it illustrates the syntax used to access nested objects in general: ``` >>> L = ['abc', [(1, 2), ([3], 4)], 5] >>> L[1] [(1, 2), ([3], 4)] >>> L[1][1] ([3], 4) >>> L[1][1][0] [3] >>> L[1][1][0][0] 3 ###### References Versus Copies ``...
In practice, this is usually what you want.
Because assignments can generate multiple references to the same object, though, it’s important to be aware that changing a mutable object in-place may affect other references to the same object **f** **|** ----- _Figure 9-1.
A nested object tree with the offsets of its components, created by running the literal_ _expression ['abc', [(1, 2), ([3], 4)], 5].
Syntactically nested objects are internally represented as_ _references (i.e., pointers) to separate pieces of memory._ elsewhere in your program.
If you don’t want such behavior, you’ll need to tell Python to copy the object explicitly. We studied this phenomenon in Chapter 6, but it can become more subtle when larger objects come into play.
For instance, the following example creates a list assigned to ``` X, and another list assigned to L that embeds a reference back to list X.
It also creates a ``` dictionary D that contains another reference back to list X: ``` >>> X = [1, 2, 3] ``` `>>> L = ['a', X, 'b']` _# Embed references to X's object_ ``` >>> D = {'x':X, 'y':2} ``` At this point, there are three references to the first list created: from the name X, from inside the list assigne...
The situation is illustrated in Figure 9-2. Because lists are mutable, changing the shared list object from any of the three references also changes what the other two reference: `>>> X[1] = 'surprise'` _# Changes all three references!_ ``` >>> L ['a', [1, 'surprise', 3], 'b'] >>> D {'x': [1, 'surprise', 3], ...
Although you can’t grab hold of the reference itself, it’s possible to store the same reference in more than one place (variables, lists, and so on).
This is a feature—you can pass a large object **|** ----- _Figure 9-2.
Shared object references: because the list referenced by variable X is also referenced from_ _within the objects referenced by L and D, changing the shared list from X makes it look different from_ _L and D, too._ around a program without generating expensive copies of it along the way.
If you really do want copies, however, you can request them: - Slice expressions with empty limits (L[:]) copy sequences. - The dictionary and set copy method (X.copy()) copies a dictionary or set. - Some built-in functions, such as list, make copies (list(L)). - The copy standard library module makes full copi...
The net effect is that changes made through X will impact only X, not L and D; similarly, ``` changes to L or D will not impact X. One final note on copies: empty-limit slices and the dictionary copy method only make _top-level copies; that is, they do not copy nested data structures, if any are present.
If_ you need a complete, fully independent copy of a deeply nested data structure, use the standard `copy module: include an` `import copy statement and say` `X = copy.deep` ``` copy(Y) to fully copy an arbitrarily nested object Y.
This call recursively traverses objects ``` to copy all their parts. This is a much more rare case, though (which is why you have to say more to make it go).
References are usually what you will want; when they are not, slices and copy methods are usually as much copying as you’ll need to do. ###### Comparisons, Equality, and Truth All Python objects also respond to comparisons: tests for equality, relative magnitude, and so on.
Python comparisons always inspect all parts of compound objects until a result can be determined.
In fact, when nested objects are present, Python automatically traverses data structures to apply comparisons _recursively from left to right, and as_ deeply as needed.
The first difference found along the way determines the comparison result. For instance, a comparison of list objects compares all their components automatically: `>>> L1 = [1, ('a', 3)]` _# Same value, unique objects_ ``` >>> L2 = [1, ('a', 3)] ``` `>>> L1 == L2, L1 is L2` _# Equivalent?
Same object?_ ``` (True, False) ``` Here, L1 and L2 are assigned lists that are equivalent but distinct objects.
Because of the nature of Python references (studied in Chapter 6), there are two ways to test for equality: - The `==` **operator tests value equivalence.
Python performs an equivalence test,** comparing all nested objects recursively. - The `is` **operator tests object identity.
Python tests whether the two are really the** same object (i.e., live at the same address in memory). In the preceding example, L1 and L2 pass the == test (they have equivalent values because all their components are equivalent) but fail the is check (they reference two different objects, and hence two different piece...
Notice what happens for short strings, though: ``` >>> S1 = 'spam' >>> S2 = 'spam' ``` **|** ----- ``` >>> S1 == S2, S1 is S2 (True, True) ``` Here, we should again have two distinct objects that happen to have the same value: ``` == should be true, and is should be false.
But because Python internally caches and ``` reuses some strings as an optimization, there really is just a single string `'spam' in` memory, shared by S1 and S2; hence, the is identity test reports a true result.
To trigger the normal behavior, we need to use longer strings: ``` >>> S1 = 'a longer string' >>> S2 = 'a longer string' >>> S1 == S2, S1 is S2 (True, False) ``` Of course, because strings are immutable, the object caching mechanism is irrelevant to your code—strings can’t be changed in-place, regardless of ho...
If identity tests seem confusing, see Chapter 6 for a refresher on object reference concepts. As a rule of thumb, the == operator is what you will want to use for almost all equality checks; is is reserved for highly specialized roles.
We’ll see cases where these operators are put to use later in the book. Relative magnitude comparisons are also applied recursively to nested data structures: ``` >>> L1 = [1, ('a', 3)] >>> L2 = [1, ('a', 2)] ``` `>>> L1 < L2, L1 == L2, L1 > L2` _# Less, equal, greater: tuple of results_ ``` (False, False, True...
The result of the last line is really a tuple of three objects—the results of the three expressions typed (an example of a tuple without its enclosing parentheses). In general, Python compares types as follows: - Numbers are compared by relative magnitude. - Strings are compared lexicographically, character by cha...
Relative` magnitude comparisons are not supported for dictionaries in Python 3.0, but they work in 2.6 and earlier as though comparing sorted (key, `value) lists.` - Nonnumeric mixed-type comparisons (e.g., 1 < 'spam') are errors in Python 3.0. They are allowed in Python 2.6, but use a fixed but arbitrary ordering ru...
By proxy, this also applies to sorts, which use comparisons internally: nonnumeric mixed-type collections cannot be sorted in 3.0. In general, comparisons of structured objects proceed as though you had written the objects as literals and compared all their parts one at a time from left to right.
In later chapters, we’ll see other object types that can change the way they get compared. **|** ----- ###### Python 3.0 Dictionary Comparisons The second to last point in the preceding section merits illustration.
In Python 2.6 and earlier, dictionaries support magnitude comparisons, as though you were comparing sorted key/value lists: ``` C:\misc> c:\python26\python >>> D1 = {'a':1, 'b':2} >>> D2 = {'a':1, 'b':3} >>> D1 == D2 False >>> D1 < D2 True ``` In Python 3.0, magnitude comparisons for dictionaries are rem...
The alternative in 3.0 is to either write loops to compare values by key or compare the sorted key/value lists manually— the items dictionary methods and sorted built-in suffice: ``` C:\misc> c:\python30\python >>> D1 = {'a':1, 'b':2} >>> D2 = {'a':1, 'b':3} >>> D1 == D2 False >>> D1 < D2 TypeError: unord...
They print as the words True and False, but now that we’re using logical tests like these in earnest, I should be a bit more formal about what these names really mean. In Python, as in most programming languages, an integer 0 represents false, and an integer 1 represents true.
In addition, though, Python recognizes any empty data structure as false and any nonempty data structure as true.
More generally, the notions of **|** ----- true and false are intrinsic properties of every object in Python—each object is either true or false, as follows: - Numbers are true if nonzero. - Other objects are true if nonempty. Table 9-4 gives examples of true and false objects in Python. _Table 9-4.
Example object truth values_ **Object** **Value** ``` "spam" True "" False [] False {} False 1 True 0.0 False None False ``` As one application, because objects are true or false themselves, it’s common to see Python programmers code tests like if X:, which, assuming X is a string, is the same as if X != '':...
In other words, you can test the object itself, instead of comparing it to an empty object.
(More on if statements in Part III.) ###### The None object As shown in the last item in Table 9-4, Python also provides a special object called ``` None, which is always considered to be false.
None was introduced in Chapter 4; it is the ``` only value of a special data type in Python and typically serves as an empty placeholder (much like a NULL pointer in C). For example, recall that for lists you cannot assign to an offset unless that offset already exists (the list does not magically grow if you make an...
To preallocate a 100-item list such that you can add to any of the 100 offsets, you can fill it with None objects: ``` >>> L = [None] * 100 >>> >>> L [None, None, None, None, None, None, None, ...
] ``` This doesn’t limit the size of the list (it can still grow and shrink later), but simply presets an initial size to allow for future index assignments.
You could initialize a list with zeros the same way, of course, but best practice dictates using None if the list’s contents are not yet known. **|** ----- Keep in mind that None does not mean “undefined.” That is, None is something, not nothing (despite its name!)—it is a real object and piece of memory, given a b...
Watch for other uses of this special object later in the book; it is also the default return value of functions, as we’ll see in Part IV. ###### The bool type Also keep in mind that the Python Boolean type bool, introduced in Chapter 5, simply augments the notions of true and false in Python.
As we learned in Chapter 5, the builtin words True and False are just customized versions of the integers 1 and 0—it’s as if these two words have been preassigned to 1 and 0 everywhere in Python.
Because of the way this new type is implemented, this is really just a minor extension to the notions of true and false already described, designed to make truth values more explicit: - When used explicitly in truth test code, the words True and False are equivalent to 1 and 0, but they make the programmer’s intent c...
Python also provides a bool builtin function that can be used to test the Boolean value of an object (i.e., whether it is True—that is, nonzero or nonempty): ``` >>> bool(1) True >>> bool('spam') True >>> bool({}) False ``` In practice, though, you’ll rarely notice the Boolean type produced by logic tests,...
We’ve looked at the most prominent of these; most of the other kinds of objects in Figure 9-3 correspond to program units (e.g., functions and modules) or exposed interpreter internals (e.g., stack frames and compiled code). The main point to notice here is that everything in a Python system is an object type and may ...
For instance, you can pass a class to a function, assign it to a variable, stuff it in a list or dictionary, and so on. **|** ----- _Figure 9-3.