file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
with open('example.txt', 'r') as file:
content = file.read()
print(content)
注意:如果文件不存在或路径错误,则会产生FileNotFoundError异常。如果读取期间发生错误,则会产生IOError异常。因此,应该使用try-except语句处理这些异常。