如何使用with open()和write()实现Python文件读写及数据持久化?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1396个文字,预计阅读时间需要6分钟。
pythonwith open('file.txt', 'r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) as f: content=f.read()
open()
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
# 默认读取整个文件,即:所有字符f = open('C:/Users/xxx/Desktop/测试读取文件.txt', 'r')
print(f.read())
f.close()
readlines()
# 一致性读取所有行。返回所有行组成的列表,列表每个元素为一行。def read_txt():
f = open('D:\\公司文档\\20190509\\test/result_general.txt', "r", encoding="utf-8")
lines = f.readlines()
data_list = []
for line in lines:
data_list.append(line.strip('\n'))
f.close()
return data_list
readline()
# readline() 每次只读取一行,通常比readlines() 慢得多。一次读取整个大文件时,才会使用。本文共计1396个文字,预计阅读时间需要6分钟。
pythonwith open('file.txt', 'r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) as f: content=f.read()
open()
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
# 默认读取整个文件,即:所有字符f = open('C:/Users/xxx/Desktop/测试读取文件.txt', 'r')
print(f.read())
f.close()
readlines()
# 一致性读取所有行。返回所有行组成的列表,列表每个元素为一行。def read_txt():
f = open('D:\\公司文档\\20190509\\test/result_general.txt', "r", encoding="utf-8")
lines = f.readlines()
data_list = []
for line in lines:
data_list.append(line.strip('\n'))
f.close()
return data_list

