>>> objfile = open(fdfile, 'r', encoding='latin1', closefd=False)
>>> objfile.read()
'Jello stdio file\nHello descriptor file\n'
>>> objfile = os.fdopen(fdfile, 'r', encoding='latin1', closefd=True)
>>> objfile.seek(0)
>>> objfile.read()
'Jello stdio file\nHello descriptor file\n'
We’ll make use of this file object wrapper technique to simplify text-oriented pipes and
other descriptor-like objects later in this book (e.g., sockets have a makefile method
which achieves similar effects).
Other os module file tools
The os module also includes an assortment of file tools that accept a file pathname
string and accomplish file-related tasks such as renaming (os.rename), deleting
(os.remove), and changing the file’s owner and permission settings (os.chown,
os.chmod). Let’s step through a few examples of these tools in action:
>>> os.chmod('spam.txt', 0o777) # enable all accesses
This os.chmod file permissions call passes a 9-bit string composed of three sets of three
bits each. From left to right, the three sets represent the file’s owning user, the file’s
group, and all others. Within each set, the three bits reflect read, write, and execute
access permissions. When a bit is “1” in this string, it means that the corresponding
operation is allowed for the assessor. For instance, octal 0777 is a string of nine “1”
bits in binary, so it enables all three kinds of accesses for all three user groups; octal
0600 means that the file can be read and written only by the user that owns it (when
written in binary, 0600 octal is really bits 110 000 000).
This scheme stems from Unix file permission settings, but the call works on Windows
as well. If it’s puzzling, see your system’s documentation (e.g., a Unix manpage) for
chmod. Moving on:
>>> os.rename(r'C:\temp\spam.txt', r'C:\temp\eggs.txt') # from, to
>>> os.remove(r'C:\temp\spam.txt') # delete file?
WindowsError: [Error 2] The system cannot find the file specified: 'C:\\temp\\...'
>>> os.remove(r'C:\temp\eggs.txt')
The os.rename call used here changes a file’s name; the os.remove file deletion call
deletes a file from your system and is synonymous with os.unlink (the latter reflects
the call’s name on Unix but was obscure to users of other platforms).† The os module
also exports the stat system call:
† For related tools, see also the shutil module in Python’s standard library; it has higher-level tools for copying
and removing files and more. We’ll also write directory compare, copy, and search tools of our own in
Chapter 6, after we’ve had a chance to study the directory tools presented later in this chapter.
File Tools | 159