[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

os.lseek( descriptor, position , how )
Moves to position in the file


Technically, os calls process files by their descriptors, which are integer codes or “han-
dles” that identify files in the operating system. Descriptor-based files deal in raw bytes,
and have no notion of the line-end or Unicode translations for text that we studied in
the prior section. In fact, apart from extras like buffering, descriptor-based files gener-
ally correspond to binary mode file objects, and we similarly read and write bytes
strings, not str strings. However, because the descriptor-based file tools in os are lower
level and more complex than the built-in file objects created with the built-in open
function, you should generally use the latter for all but very special file-processing
needs.*


Using os.open files


To give you the general flavor of this tool set, though, let’s run a few interactive ex-
periments. Although built-in file objects and os module descriptor files are processed
with distinct tool sets, they are in fact related—the file system used by file objects simply
adds a layer of logic on top of descriptor-based files.


In fact, the fileno file object method returns the integer descriptor associated with a
built-in file object. For instance, the standard stream file objects have descriptors 0, 1,
and 2; calling the os.write function to send data to stdout by descriptor has the same
effect as calling the sys.stdout.write method:


>>> import sys
>>> for stream in (sys.stdin, sys.stdout, sys.stderr):
... print(stream.fileno())
...
0
1
2

>>> sys.stdout.write('Hello stdio world\n') # write via file method
Hello stdio world
18
>>> import os
>>> os.write(1, b'Hello descriptor world\n') # write via os module
Hello descriptor world
23

Because file objects we open explicitly behave the same way, it’s also possible to process
a given real external file on the underlying computer through the built-in open function,
tools in the os module, or both (some integer return values are omitted here for brevity):



  • For instance, to process pipes, described in Chapter 5. The Python os.pipe call returns two file descriptors,
    which can be processed with os module file tools or wrapped in a file object with os.fdopen. When used with
    descriptor-based file tools in os, pipes deal in byte strings, not text. Some device files may require lower-level
    control as well.


156 | Chapter 4: File and Directory Tools

Free download pdf