[英]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.