Python读写文件

读文件

handle=open("test.txt","r")
# 方法一
data=handle.read()
# data=handle.readline()	# read just one line
# data=handle.readlines()
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!") 

你可能感兴趣的:(Python)