Python从0到1——文件操作
其他常用操作见:https://blog.csdn.net/qq_33302004/article/details/112859327
# 1.读整个文件
txt = open('./hello.txt')
txt_str = txt.read()
print(txt_str)
txt.close()
# 2.按行读文件
txt = open('./hello.txt')
txt_lines = txt.readlines()
print(txt_lines)
for line in txt_lines:
print(line)
txt.close()
# 3.写文件
txt = open('./hello.txt','w') # 覆盖式写入
txt.write('have a nice day\n')
txt.write('guo zhi yuan\n')
txt.close() # 记得要close()
txt = open('./hello.txt','a') # 追加式写入
txt.write('123\n')
txt.write('456\n')
txt.close()
# 4.使用with(常用)
with open('./hello.txt','w') as f:
f.write('have a nice day\n')
f.write('guo zhi yuan\n')
f.close() # 其实会自动关闭文件