我想在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
答案 0 :(得分:3)
您可以写入 tempfile ,然后替换原始文件:
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")
您也可以将 fileinput 与 inplace = True 一起使用
: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
答案 1 :(得分:0)
这是一个将现有文件内容复制到临时文件的解决方案。根据需要修改它。然后写回原始文件。 来自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