[英]Append each line in file
我想在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
您可以写入临时文件然后替换原始文件:
from tempfile import NamedTemporaryFile
from shutil import move
data = ["Yes", "No"]
with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
# pair up lines and each string
for arg, line in zip(data, f):
# remove the newline and concat new data
temp.write(line.rstrip()+" {}\n".format(arg))
# replace original file
move(temp.name,"in.txt")
你也可以使用inin = true的 fileinput :
import fileinput
import sys
for arg, line in zip(data, fileinput.input("in.txt",inplace=True)):
sys.stdout.write(line.rstrip()+" {}\n".format(arg))
输出:
Is it funny? Yes
Is it dog? No
这是一个将现有文件内容复制到临时文件的解决方案。 根据需要修改它。 然后写回原始文件。 来自这里的灵感
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.