简体   繁体   English

Python 将 txt 写入列中的 csv

[英]Python writing txt to csv in columns

I am trying to write the data from the.txt file to the csv.我正在尝试将 .txt 文件中的数据写入 csv。 I am first reading the data from the.txt files and only those which are tagged with specific strings.我首先从 .txt 文件中读取数据,并且只读取带有特定字符串标记的数据。 I am then modifying these data by removing the tag strings.然后我通过删除标签字符串来修改这些数据。

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

This is the code I am using, at first I am trying to count how many inputs I have and assign it to y.这是我正在使用的代码,起初我试图计算我有多少输入并将其分配给 y。 In the original text file each input has a specific local time to it thus in the TimeThread I am trying to convert this local time from.txt to csv and put them in columns.在原始文本文件中,每个输入都有一个特定的本地时间,因此在 TimeThread 中,我试图将此本地时间从.txt 转换为 csv 并将它们放在列中。 The p=s[5:len(s)] just modifies the string by removing the tag string and just leaving the time like '2020-06-14 13:24:04'. p=s[5:len(s)] 只是通过删除标签字符串来修改字符串,只留下像'2020-06-14 13:24:04'这样的时间。

In my test txt file I have just two time inputs and whenever I run this code the only the last input gets written to the.csv file in [1,A1], could anybody help me on how to fix this code and write both inputs to the.csv without overwriting?在我的测试 txt 文件中,我只有两个时间输入,每当我运行此代码时,只有最后一个输入被写入 [1,A1] 中的 .csv 文件,有人可以帮我解决如何修复此代码并编写两个输入到.csv 不覆盖?

Thanks!谢谢!

Replace this line替换此行

with open('userInfo.csv', 'w') as time
With
with open('userInfo.csv', 'a+') as time

Since you were using w as Write mode the file was replaced everytime and only last value persisted由于您使用 w 作为写入模式,因此每次都替换文件并且仅保留最后一个值

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

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