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!')
本文介绍了如何使用Python逐块读取文本文件和二进制文件的方法,并演示了如何进行文件的写入操作。此外,还展示了如何利用with语句来确保文件在使用完毕后能够正确关闭,以及如何捕获错误来处理文件读取过程中可能出现的问题。
831

被折叠的 条评论
为什么被折叠?



