【问题标题】:Writing to File Next Line写入文件下一行
【发布时间】:2014-05-07 22:22:51
【问题描述】:

我正在尝试从文件中获取数字,为它们分配一个变量名,对变量进行一些数学运算,然后写入文件的下一行。例如,如果我有一个文件:1 2 3 4 5,这是我到目前为止的缩写代码(Python 3.3)。我遇到的唯一问题是将计算结果写在下一行。预先感谢您的帮助。

with open('test.txt', 'r') as f:
     read_data = f.read()
     a1 = (read_data[0])`a1 = (read_data[0])
print(a1) # this is just a test to see whats happening
f.close()
with open('test.txt','w') as f:
    f.write(a1) #how do I get a1  to write on the next line of the file 
exit()

【问题讨论】:

  • 我认为以'a' 模式打开文件而不是'w' 应该会有所帮助。这会将文本附加到文件而不是覆盖。

标签: python file line next


【解决方案1】:
with open('test.txt', 'r') as f:
    data = f.read()
with open('test.txt', 'w') as f:
    for line in data.split('\n'):
        a1 = line # You didn't specify what modifications you did with the data so...
        f.write(line + '\n')
        f.write(a1 + '\n')

另请注意,我省略了f.close(),因为您不需要它。
忘了它叫什么(上下文管理器旁边的另一个花哨的词),但with 是一个自动关闭语句,每当你离开块f 时,Python 会自动调用.close()

由于你没有写出你想要做什么样的计算,这里是一个虚构的例子:

with open('test.txt', 'r') as f:
    data = f.read()
with open('test.txt', 'w') as f:
    for line in data.split('\n'):
        a1 = int(line)*100
        f.write(line + '\n')
        f.write(str(a1) + '\n')

还阅读了您在下一行提到的示例,但您没有指定数据是否已经按行分隔,因此从 djas 中获取答案,您可以将它们合并到:

with open('test.txt', 'r') as f:
    data = f.read()
with open('test.txt', 'w') as f:
    for line in data.split():
        a1 = int(line)*100
        f.write(line + '\n')
        f.write(str(a1) + '\n')

【讨论】:

  • 谢谢,但是把a1的值放在文件第一行的末尾,希望把a1的值放在下一行的开头。
  • @user3472574 我明白了,所以你想读第一行,做点什么,把它写到第二行,然后读过去的第二行 aaa 并重复?如果是这样,如果您在线显示您想要完成的“工作”类型会有所帮助,因为上面的代码毫无意义a1 = (read_data[0])'a1 = ... 这很奇怪。
【解决方案2】:

假设您的输入文件看起来像

04 80 52 67

,以下代码有效:

with open('input.txt', 'r') as f:
    line = f.read()

with open('output.txt','w') as f:
    for element in line.split():  
        f.write("%s\n" % ''.join(element))

编辑:您还可以将 f.write("%s\n" % ''.join(element)) 替换为 f.write(element+'\n') 并按照 @Torxed 的建议删除 f.close()。

【讨论】:

  • 也跳过.close() :) 因为这是with 的重点。
【解决方案3】:

with open 自动关闭文件,因此您可以在with open 语句中执行程序的主要逻辑。例如,这个程序会做你需要的:

with open('test.txt', 'r') as f:
  lines = f.readlines()
newlines = []
for line in lines:
  newlines.append(line)
  newline = #do some logic here
  newlines.append(newline)
with open('test.txt','w') as f:
  for line in newlines:
    f.write(line + '\n')

如果只有一行,可以去掉for line in lines:循环,直接修改文件。

另一方面,如果您希望这是一个迭代过程,如其中一个问题的 cmets 所示,即您希望新的第二行成为新的第一行,以此类推,您可以将上述内容放入某个函数中,如下所示:

def func(first_line_index):
  """
  Takes the index of the current first line as first_line_index and modifies
  the next line as per your assignment, then writes it back to the file
  """
  with open('test.txt', 'r') as f:
    lines = f.readlines()
  line1 = lines[first_line_index]
  newlines = []
  for line in lines[:first_line_index+1]:
    newlines.append(line)
  newlines.append(lines[first_line_index])
  newline = #do some logic here based on the line above
  newlines.append(newline)
  for line in lines[first_line_index+2:]:
    newlines.append(line)
  with open('test.txt','w') as f:
    for line in newlines:
      f.write(line + '\n')

def __main__():
  counter = 0
  while #some condition- depends on your assignment:
    func(counter)
    counter += 1

【讨论】:

    猜你喜欢
    • 2013-10-18
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多