我想在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