Python txt文件读取和写入,open()打开文件和读取文件内容,.readline()和.readlines()读取文件的区别和应用,with open

Python txt文件读取和写入,open()打开文件和读取文件内容,.readline()和.readlines()读取文件的区别和应用,with open,第1张

open()打开文件并写入内容

打开文件:

#打开需要读取的文件
input_file = open('example.txt','r',encoding='utf-8')
#打开需要写入的文件,如果没有即创建一个新的文件
output_file = open('example_out.txt','w',encoding='utf-8')

读取文件内容,一次性全部读取,返回列表形式,用.readlines(),在读取大文件时比较耗内存,容易宕机:

content = input_file.readlines()
print(content)

读取文件内容,一次只读取一行,用.readline(),如果不遍历读取,默认只读取第一行(注意:这个比较适合特别大型的文件):

lis_duqu = []
while True:
    content = input_file.readline()
    if content:
        lis_duqu.append(content)
    else:
        break
print(lis_duqu)

 写入文件:

注意写入文件时只能按行写入,而且必须是字符串的格式:

方法一:

content = input_file.readlines()
for i in content:
    output_file.write(i)

方法二:

while True:
    content = input_file.readline()
    output_file.write(content)
    if not content:
        break

 通常用法,用with open() as f:方法来读取和写入文件:

with open('example.txt','r',encoding='utf-8') as f:
    for line in f.readlines():
        output_file.write(line)

或者:

with open('example.txt','r',encoding='utf-8') as f:
    for i in range(2):
        line = f.readline()
        output_file.write(line)

最后,关闭文件,省内存开销:

f.close()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/736624.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存