【发布时间】: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'应该会有所帮助。这会将文本附加到文件而不是覆盖。