【问题标题】:Append each line in file附加文件中的每一行
【发布时间】:2016-10-18 19:00:14
【问题描述】:

我想在python中追加文件中的每一行例如:

文件.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

【问题讨论】:

  • 您必须读取文件的每一行并用修改后的行覆盖它们
  • 我不认为这是一个非常糟糕的问题。为什么人们不赞成它?不过我也不会赞成。
  • 我花了一些时间来理解这个问题,即使这样我也不能完全确定它的意思。也许可以改写。
  • @wwl 问题中给出了示例。
  • 正如@PatrickHaugh 所说,“追加”仅追加在文件末尾,而不是在每一行的末尾->您必须用整个修改后的行覆盖该行

标签: python python-3.x


【解决方案1】:

你可以写入一个 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")

您也可以将 fileinputinplace=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

【讨论】:

  • 我需要这个Is it funny? Yes Is it dog? No 不是这个Is it funny? Is it dog?Is it funny? Yes Is it dog? Yes
  • 我在我的代码中添加了temp.write(line.rstrip()+" {}\n".format(arg)) 并给出了Is it funny? Is it dog?Is it funny? Yes Is it dog? Yes
  • @Amar,这是不可能的,因为您可以清楚地看到字符串中添加了换行符。唯一可能的方法是文件中有一行。这也改变了原始文件,所以不确定你在做什么。
  • 数据必须先存到其他文件再写入吗?
  • @Amar 检查文件并再次运行脚本,它给出了 Padriac 发布的正确结果。
【解决方案2】:

这是一种将现有文件内容复制到临时文件的解决方案。根据需要对其进行修改。然后写回原始文件。 灵感来自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

【讨论】:

  • 我需要这个Is it funny? Yes Is it dog? No
  • 就是上面会提供的,下面是代码执行后的文件内容:Is it funny?YesIs it dog?No
  • 是的,先生。这就是我们在这里所做的。我们正在将原始文件复制到临时文件。然后用修改后的数据更新原始文件
  • 两点说明: 1. 如果您可以重命名文件,则逐行复制文件有点过分 2. 语法with open(file) as i: 而不是i = open(file) 提供了更清晰的代码和清晰的视觉分隔文件的使用位置。
  • @Anil_M 请详细说明这一行t.seek(0) Rewind 是什么意思?
猜你喜欢
  • 2022-11-11
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 2013-09-05
  • 1970-01-01
  • 2015-02-27
  • 2017-11-23
相关资源
最近更新 更多