io

Table of Contents

open

buffering
0
unbuffered (read and write are one system call and can return short)
1
line buffered (only usable if universalnewlines=True i.e., in a text mode)
any other positive value
use a buffer of approximately that size
negative bufsize (the default)

the default buffering policy as follows:

  • binary files use io.DEFAULT_BUFFER_SIZE
  • interactive text files(files for which isatty() returns True) use line buffering.
  • In other words, even sys.stdout can be fully buffered if it runs as a background proces
Returns
  • binary files are instances of BytesIO
  • text files are instances of StringIO

readline

An useful idiom is:

with open('mydata.txt') as f:
    for line in iter(f.readline, ''):
        process_line(line)
# Following codes will block until the file is ready
for line in f:
    pass

ls = f.readlines()

When the buffer is flushed? discussion

Read a file except the first line howto

with open(fname) as f:
    next(f)
    for line in f:
        #do something