File IO - Reading and Writing
f = open('output.txt', 'w', encoding="utf-8")
f = open('output.txt')
....
f.close()
r | read ( default ) |
w | write ( overwrite ) |
a | append |
r+ | read and write |
b | binary mode |
- textmode
- binary mode
encoding:
- default encoding is platform dependent, UTF-8 recommended
- can’t be specified with binary mode
\n Unix line ending \r\n Windows line ending
For Windows:
- on read, line ending \r\n is converted to \n
-
on write, line ending \n is converted to \r\n
- if a file isn’t closed, cached results may not be written to disk ( even after script exit )
- using “with” will make sure that a file is automatically closed. ( Still works when exceptions occur. )
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
- read size chars in txt mode
- read size bytes in binary mode
- return empty string at end of 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')
- can write a string or bytes object
f.tell() # get current position in file
Change position in file:
f.seek(offset, whence)
- offset - offset from whence
- whence - a reference point
- whence values
- 0 begining of file
- 1 current position
- 2 end of file
f.seek(offset) # whence defaults to zero ( beginning )
f = open('output.dat', 'rb+')
f.write(b'jdiji63486jfeifje32233cen3oi23')
f.seek(7) # move to 8th byte
f.read(1)
f.seek(-4, 2) # move to 4th byte
f.read(1)
””” 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:
f.closed
isatty()
truncate()