Python在列中将txt写入csv
我正在尝试将.txt文件中的数据写入csv。我首先读取.txt文件中的数据,并且只读取带有特定字符串标记的数据。然后通过删除标记字符串修改这些数据Python在列中将txt写入csv,python,csv,Python,Csv,我正在尝试将.txt文件中的数据写入csv。我首先读取.txt文件中的数据,并且只读取带有特定字符串标记的数据。然后通过删除标记字符串修改这些数据 import substring import codecs import threading import csv global y with open('output.txt', "r",encoding="utf-8") as input: y = 0 for line in input:
import substring
import codecs
import threading
import csv
global y
with open('output.txt', "r",encoding="utf-8") as input:
y = 0
for line in input:
if line.startswith('Warmateba:'):
y=y+1
class TimeThread(threading.Thread):
def run(self):
with open('output.txt', "r",encoding="utf-8") as input:
for line in input:
if line.startswith('Warmateba:'):
s = (next(input))
p = s[5:len(s)]
print(p)
with open('userInfo.csv', 'w') as time:
for i in range(0,y)
writer = csv.writer(time, delimiter=' ')
writer.writerow(p)
time_thread=TimeThread()
time_thread.start()
time_thread.join()
这是我正在使用的代码,首先我试图计算我有多少输入并将其分配给y。在原始文本文件中,每个输入都有一个特定的本地时间,因此在TimeThread中,我试图将这个本地时间从.txt转换为csv,并将它们放在列中。p=s[5:len(s)]只是通过移除标记字符串来修改字符串,并只保留“2020-06-14 13:24:04”这样的时间
在我的测试txt文件中,我只有两个时间输入,每当我运行此代码时,只有最后一个输入会写入[1,A1]中的.csv文件,有人能帮助我修复此代码并将两个输入写入.csv而不覆盖吗
谢谢 更换此线路
with open('userInfo.csv', 'w') as time
With
with open('userInfo.csv', 'a+') as time
由于您使用w作为写入模式,因此每次都会替换该文件,并且只有最后一个值保持不变替换此行
with open('userInfo.csv', 'w') as time
With
with open('userInfo.csv', 'a+') as time
由于您使用w作为写入模式,因此每次都会替换该文件,并且只有最后一个值保持不变欢迎使用StackOverflow。代码缩进是否正确?和output.txt:您已经在两个地方打开它进行阅读。也许你应该读一读。欢迎来到StackOverflow。代码缩进是否正确?和output.txt:您已经在两个地方打开它进行阅读。也许你应该读一本。是的,我当然修好了,我真傻,谢谢你。我还删除了for循环,因为它是不必要的。是的,我当然修复了它,我真傻,谢谢。我还删除了for循环,因为它是不必要的。