Python Frequently Asked Questions, Release 3.9.5 55 4.4. Input and Output To close the underlying C file descriptor for one of these three, you should first be sure that’s what you really want to do (e.g., you may confuse extension modules trying to do I/O). If it is, use$_{os.close()}$ : But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running$_{sys.stdout.close()}$ marks the Python-level file object as being closed, but does not close the associated C file descriptor. For most file objects you create in Python via the built-in$_{open()}$ function,$_{f.close()}$ marks the Python file object as being closed from Python’s point of view, and also arranges to close the underlying C file descriptor. This also happens automatically in$_{f}$’s destructor, when$_{f}$ becomes garbage. Python file objects are a high-level layer of abstraction on low-level C file descriptors. 4.4.6 Why doesn’t closing sys.stdout (stdin, stderr) really close it? 4.4.5 How do I access the serial (RS232) port? 4.4.4 I can’t seem to use os.read() on a pipe created with os.popen(); why? 4.4.3 How do I read (or write) binary data? 4.4.2 How do I copy a file? The$_{shutil}$ module contains a$_{copyfile()}$ function. Note that on MacOS 9 it doesn’t copy the resource fork and Finder info. To read or write complex binary data formats, it’s best to use the$_{struct}$module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa. For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file: The ‘>’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string. For data that is more regular (e.g. a homogeneous list of ints or floats), you can also use the$_{array}$ module. Note: To read and write binary data, it is mandatory to open the file in binary mode (here, passing$_{"rb"}$ to open() ). If you use$_{"r"}$ instead (the default), the file will be open in text mode and$_{f.read()}$ will return$_{str}$ objects rather than$_{bytes}$objects. import struct with open(filename, "rb") as f: s =f.read(8) x, y, z=struct.unpack( ">hhl", s) os.read() is a low-level function which takes a file descriptor, a small integer representing the opened file.$_{os.}$ popen() creates a high-level file object, the same type returned by the built-in$_{open()}$ function. Thus, to read n bytes from a pipe p created with$_{os.popen()}$ , you need to use$_{p.read(n)}$ . https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com For Unix, see a Usenet post by Mitch Chapman: http://pyserial.sourceforge.net For Win32, POSIX (Linux, BSD, etc.), Jython: