python open 追加_python-在文件中追加每一行

我想在python文件中附加每一行,例如:

File.txt

Is it funny?

Is it dog?

预期结果

Is it funny? Yes

Is it dog? No

假设是,否.我这样做:

with open('File.txt', 'a') as w:

w.write("Yes")

但它会附加在文件末尾.并非每一行.

编辑1

with open('File.txt', 'r+') as w:

for line in w:

w.write(line + " Yes ")

这就是结果

Is it funny?

Is it dog?Is it funny?

Yes Is it dog? Yes

我不需要这个.它正在添加带有附加字符串的新行.

我需要

Is it funny? Yes

Is it dog? No

解决方法:

这是将现有文件内容复制到临时文件的解决方案.根据需要对其进行修改.然后写回原始文件.

灵感来自here

import tempfile

filename = "c:\\temp\\File.txt"

#Create temporary file

t = tempfile.NamedTemporaryFile(mode="r+")

#Open input file in read-only mode

i = open(filename, 'r')

#Copy input file to temporary file

for line in i:

#For "funny" add "Yes"

if "funny" in line:

t.write(line.rstrip() + "Yes" +"\n")

#For "dog" add "No"

elif "dog" in line:

t.write(line.rstrip() + "No" +"\n")

i.close() #Close input file

t.seek(0) #Rewind temporary file

o = open(filename, "w") #Reopen input file writable

#Overwriting original file with temp file contents

for line in t:

o.write(line)

t.close() #Close temporary file

标签:python-3-x,python

来源: https://codeday.me/bug/20191118/2025207.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值