[英]How would i append two lists already on a txt file?
I want to be able to create two lists: Time and data. 我希望能够创建两个列表:时间和数据。
import time
date = [time.strftime("%Y/%m/%d %I:%M%p")]
data = []
x = input()
data.append(x)
with open("RapData.txt", "a") as output:
output.write(str(date))
output.write(str(data))
This code makes the two lists and saves it all on one line in the txt file like this if ran twice: 如果运行两次,此代码将创建两个列表并将其全部保存在txt文件的一行中:
['2017/06/28 02:15PM']['x']['2017/06/28 02:15PM']['x']
and i want it to be: 我希望它是:
['2017/06/28 02:15PM']['2017/06/28 02:15PM']
['x']['x']
You need to write the newline character to the file as well: 您还需要将换行符写入文件:
import time
date = [time.strftime("%Y/%m/%d %I:%M%p")]
f = open("RapData.txt", "a")
data = [input()]
f.write(str(date))
f.write('\n')
f.write(str(data))
To achieve what you are asking for you can't use append (as append adds items to the end of the file). 要实现您的要求,您不能使用append(因为append将项目添加到文件的末尾)。
You would need to read the data to a local variable and output it to the file again: 您需要将数据读取到局部变量,然后再次将其输出到文件:
open("RapData.txt","r")
... read code...
open("RapData.txt","w")
... write code..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.