写入到文件下一行



我试图从文件中获取数字,为它们分配一个变量名称,对变量进行一些数学运算,并写入文件中的下一行。如果我有一个文件,例如: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()
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')

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

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("%sn" % ''.join(element))

编辑:您也可以替换f.write("%sn" % ''.join(element))f.write(element+'n')和删除f.k close(),建议@Torxed.

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:循环,直接修改文件。

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

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

相关内容

  • 没有找到相关文章

最新更新