[英]Append each line in file
I want to append each line in file in python
For example: 我想在
python
追加文件中的每一行例如:
File.txt FILE.TXT
Is it funny?
Is it dog?
Expected Result 预期结果
Is it funny? Yes
Is it dog? No
Assume that YES, No is given. 假设是,否,给出。 I am doing in this way:
我这样做:
with open('File.txt', 'a') as w:
w.write("Yes")
But it appends at the end of file. 但它附加在文件的末尾。 Not on every line.
不是每一行。
Edit 1 编辑1
with open('File.txt', 'r+') as w:
for line in w:
w.write(line + " Yes ")
This is giving the result 这是结果
Is it funny?
Is it dog?Is it funny?
Yes Is it dog? Yes
I do not need this.It is adding new line with appended string. 我不需要这个。它正在添加带有附加字符串的新行。 I need
我需要
Is it funny? Yes
Is it dog? No
You can write to a tempfile then replace the original: 您可以写入临时文件然后替换原始文件:
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")
You could also use fileinput with inplace=True : 你也可以使用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))
Output: 输出:
Is it funny? Yes
Is it dog? No
Here is a solution that copies existing file content to a temp file. 这是一个将现有文件内容复制到临时文件的解决方案。 Modifies it as per needs.
根据需要修改它。 Then writes back to original file.
然后写回原始文件。 Inspiration from 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.