第十章 文件与异常
1 文件中读出数据
读整个文件 with open('pi_digits.txt') as file_object
加入文件路径
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
逐行读取:
with open(filename) as file_object:
for line in file_object:
print(line)
创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
2 写入文件:
写入空文件
读取模
式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
写入多行:
附加文件:
with open(filename, 'a') as file_object:
3 异常:
try...except
4 存储数据:
json.dump() json.load()
重构
浙公网安备 33010602011771号