读文件
handle=open("test.txt","r")
data=handle.read()
print(data)
for line in handle:
print(line)
while True:
data=handle.read(1024)
print(data)
if not data:
break
handle.close()
写文件
handle=open("test.txt","w")
handle.write("This is a test!")
handle.close()
使用上下文管理器
with open("test.txt","r") as file_handler:
for line in file_handler:
print(line)
捕获异常
try:
file_handler=open("test.txt")
for line in file_handler:
print(line)
except IOError:
print("An IOError has occurred!")
finally:
file_handler.close()
try:
with open("test.txt") as file_handler:
for line in file_handler:
print(line)
except IOError:
print("An IOError has occurred!")