您当前的位置:首页 > 计算机 > 编程开发 > Python

python 文本文件读写的 3 种方法

时间:12-14来源:作者:点击数:

第一种方法:

file1 = open("test.txt")
file2 = open("output.txt","w")

while True:
    line = file1.readline()
    #这里可以进行逻辑处理
    file2.write('"'+line[:s]+'"'+",")
    if not line:
        break
#记住文件处理完,关闭是个好习惯
file1.close()
file2.close()

读文件有3种方法:

  • read() 将文本文件所有行读到一个字符串中。
  • readline() 是一行一行的读
  • readlines() 是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。

优点:readline() 可以在读行过程中跳过特定行。

第二种方法:

文件迭代器,用 for 循环的方法

file2 = open("output.txt","w")
for line in open("test.txt"):
      #这里可以进行逻辑处理
    file2.write('"'+line[:s]+'"'+",")

第三种方法:

文件上下文管理器

with open('somefile.txt', 'r') as f:
    data = f.read()

# Iterate over the lines of the file
with open('somefile.txt', 'r') as f:
    for line in f:
        # process line

# Write chunks of text data
with open('somefile.txt', 'w') as f:
    f.write(text1)
    f.write(text2)
    ...

# Redirected print statement
with open('somefile.txt', 'w') as f:
    print(line1, file=f)
    print(line2, file=f)
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐