How to Read Files Piece by Piece
h = open('test.txt', 'r')
for line in h:
print(h)
h.close()
# read the file in chunks (for binary mode)
h = open('test.txt', 'r')
while True:
data = h.read(1024)
print(data)
if not data:
break
h.close()
How to Read Binary File
h = open('test.pdf', 'rb')
How to Write Files
# `w` for write-mode, `wb` for write-binary-mode
h = open('test.txt', 'w')
h.write('ssdfsdf')
h.close()
'''
The file handle also has a `writelines` method that will accept a list of strings that the handle will write to disk in order.
'''
Using the with
operator
The with
operator creates what is known as context manager in PYthon that will automatically close the file for you when you are done with processing it.
with open('test.txt', 'r') as h:
for line in h:
print(line)
Once you leave the with
block, the file handle will close and you won’t be able to use it any more.
Catching Errors
try:
h = open('test.txt', 'r')
for line in h:
print(line)
except IOError:
print('An IOError has occurred!')
finally:
h.close()
Do the same thing using with
try:
with open('test.txt', 'r') as h:
for line in h:
print(line)
except IOError:
print('An IOError has occurred!')