Python input/output

From wikinotes
Revision as of 18:20, 15 February 2019 by Will (talk | contribs) (→‎sockets)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Concepts

Most of python's in/out centers around file-descriptors, pipes, or other stream objects. The idea is that not the entire stream needs to be loaded into memory before the item is read.

stream objects

You generally need to open a stream object for reading/writing. Here are the ways you can do so:

'w'           # write
'r'           # read
'a'           # append

# modifiers
'r+'          # read + write
'rb', 'wb'    # (b) indicates read or write raw bytes


Once it is open, you can work with it:

fd.read()          # read entire stream
fd.write('text')   # write to file-descriptor
fd.seek(5)         # go to the Nth character in the stream
fd.tell()          # print current character in the stream

for line in fd:
    print(line)

files

with open('/path/to/file.txt', 'r') as fd:
    for line in fd.readlines():
        print(line)

with open('/path/to/file.txt', 'w') as fd:
    fd.write('awesome')

stdin/stdout/stderr

when something is piped to your python program, it is exposed as sys.stdin.

sys.stdin
sys.stdout
sys.stderr

reading from stdin if there is not no input causes an indefinite wait time. You can check if something is available to read from stdin using the following (works on both windows and linux -- tested).

import sys

if sys.stdin.isatty():
    print('no stdin input')
else:
    print('stdin can be read from')

io.StringIO

Sometimes it is useful to operate on a fake file-descriptor that lives in memory.

import io
fd = io.StreamIO()
fd.write('abc\n')
fd.write('def\n')

print(fd.getvalue())
>>> abc
>>> def

fd.close()

sockets

You can read/write sockets. See python networking.

pprint

import pprint

# default pprint
pprint.pprint({'a': 1, 'b':2})

# custom pprint
pp = pprint.PrettyPrinter(indent=2, width=1)
pp.pprint({'a': 1, 'b':2})