我正在尝试从文件中获取数字,为它们分配变量名称,对变量进行一些数学运算,然后写入文件中的下一行。例如,如果我有一个文件: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()
答案 0 :(得分:0)
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')
答案 1 :(得分:0)
假设您的输入文件类似于
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()。
答案 2 :(得分:0)
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