简体   繁体   English

将变量保存并附加到 txt 文件

[英]Saving and appending variables to txt file

I'm using several variables into a list variable, when the job is done I'd like to save this variable into a txt file for further use.我在一个列表变量中使用了几个变量,当工作完成后,我想将此变量保存到一个 txt 文件中以供进一步使用。

This code works except that it does not append in the txt file in a new line (although I've used \\n for new line) but it just increases the variable on the same line.这段代码有效,只是它没有在 txt 文件中追加新行(尽管我使用了\\n作为新行),但它只是增加了同一行上的变量。

ess[0].append(ess_e), ess[1].append(essv), ess[2].append(essp), ess[3].append(essq), ess[4].append(ess_s), ess[5].append(ess_d)
file = open("relais.txt", "w")
file.write(repr(ess) + "\n")
file.close()

First run of the procedure is fine, here's the txt file程序的第一次运行很好,这是txt文件

[[datetime.datetime(2021, 7, 18, 11, 31, 35, 4978)], ['61'], ['mo'], ['145'], [datetime.datetime(2021, 7, 18, 11, 31, 42, 3653)], [datetime.timedelta(seconds=6, microseconds=998675)]]

But the 2nd run gives me this, in 1 line但是第二次运行给了我这个,在 1 行

[[datetime.datetime(2021, 7, 18, 11, 31, 35, 4978), datetime.datetime(2021, 7, 18, 11, 33, 33, 920715)], ['61', '54'], ['mo', 'kj'], ['145', '10'], [datetime.datetime(2021, 7, 18, 11, 31, 42, 3653), datetime.datetime(2021, 7, 18, 11, 33, 42, 932126)], [datetime.timedelta(seconds=6, microseconds=998675), datetime.timedelta(seconds=9, microseconds=11411)]]

And I'd like the result to be with the first result on line 1 and the 2nd on line 2 and so on.我希望结果是第 1 行的第一个结果和第 2 行的第二个结果,依此类推。

How do I tell him to write it as a line and not to merge the variable fields together to get this?我如何告诉他把它写成一行而不是将变量字段合并在一起来得到这个?

[[datetime.datetime(2021, 7, 18, 11, 31, 35, 4978)], ['61'], ['mo'], ['145'], [datetime.datetime(2021, 7, 18, 11, 31, 42, 3653)], [datetime.timedelta(seconds=6, microseconds=998675)]]
[[datetime.datetime(2021, 7, 18, 11, 33, 33, 920715)], ['54'], ['kj'], ['10'], [datetime.datetime(2021, 7, 18, 11, 33, 42, 932126)], [datetime.timedelta(seconds=9, microseconds=11411)]]

The reason why adding \\n doesn't work is because the data isn't in rows, it's grouped by field.添加\\n不起作用的原因是因为数据不在行中,它是按字段分组的。 I've used a list comprehension to take the grouped data and turn it into rows.我使用列表理解来获取分组数据并将其转换为行。 Then you can use \\n".join( to take each row and join it with a newline, giving your expected output.然后你可以使用\\n".join(来获取每一行并用换行符连接它,给出你预期的输出。

rows = [[group[n] for group in ess] for n in range(len(ess[0]))]
file = open("relais.txt", "w")
file.write("\n".join([repr(x) for x in rows]))
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM