# coding=utf-8
# 覆盖写入
def save_to_file(file_name, content):
with open(file_name, 'w', encoding='utf-8') as f:
f.write(content)
if __name__ == '__main__':
save_to_file('./test.txt', '这是要写入的内容')
# 循环写入
with open('./test.txt', 'a', encoding='utf-8') as f:
for i in range(0,10):
f.write(str(i) + '\n')
# 读取文件
with open('./test.txt', 'r', encoding='utf-8') as f:
lines = f.readlines() # 按行读取所有文件内容至变量lines
for line in lines:
print(line)
Python读写文本文件
2024-06-11阅读数:290
下一篇:Python爬取图片并保存