简体   繁体   English

我将如何在txt文件上附加两个列表?

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

相关问题 如果文件中已存在文本,如何添加两个换行符? - How do I append two newlines if text already exists in file? 如何附加到两个单独的列表? - How do I append to two separate lists? 如何将此 txt 文件解析为 csv? - How would I parse this txt file into csv? 如何在txt文件中添加两个列表,以便它们留在两个不同的列中并用逗号分隔? (蟒蛇) - how can i add two lists in a txt file so they stay in two different columns and are separated by a comma? (Python) 两个如何按列写入两个嵌套列表 in.txt 文件? - How two write two nested lists column wise in .txt file? 如何将两个相互匹配的列表输出到一个txt文件中 - How to output two lists match to each other into a txt file 我想看看新发现的美丽汤链接是否已经在 queue.txt 文件和 crawled.txt 文件中 - I would like to find if the new found links from Beautiful soup is already in the queue.txt file and crawled.txt file 如何在python中按顺序附加两个列表? - How can I append two lists in sequential order in python? 我将如何从 Ironpython 2.7 中的两个列表制作字典 - how would i make a dictionary from two lists in ironpython 2.7 我如何将这些数据分成两个单独的列表,分别为 python 中的 plot? - How would I split these data in to two separate lists to plot in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM