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

第一种方法:
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)

转载于:https://my.oschina.net/shshi/blog/182823

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值