学习记录一:文件与异常

Posted on 2019-01-02 23:17  暗夜光明  阅读(49)  评论(0)    收藏  举报

第十章 文件与异常
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()
重构

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3