Low Orbit Flux Logo 2 F

File IO - Reading and Writing

f = open('output.txt', 'w', encoding="utf-8")
f = open('output.txt')

r read ( default )
w write ( overwrite )
a append
r+ read and write
b binary mode


\n Unix line ending \r\n Windows line ending

For Windows:

with open('output.txt', encoding="utf-8") as f:
    data = f.read()

f.read()     # read entire file
f.read(size) # read limited mount from file

f.readline()  # read a single line

Loop directly over file object ( fast and memory efficient ):

for line in f:
    print(line, end='')

list(f)        # read all lines as a list
f.readlines()  # read all lines as a list

Write string to a file, return character count written:

f.write('This is a test\n')

f.tell()  # get current position in file

Change position in file:

f.seek(offset, whence)

f.seek(offset)  # whence defaults to zero ( beginning )

f = open('output.dat', 'rb+')

f.seek(7)      # move to 8th byte

f.seek(-4, 2)  # move to 4th byte

””” In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour.”””

Check if closed: