简体   繁体   中英

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.

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.

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

[[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

[[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.

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. 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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