【问题标题】:Sort through an csv file and copy only the rows with an keyword in the header对 csv 文件进行排序并仅复制标题中带有关键字的行
【发布时间】:2020-10-08 20:31:03
【问题描述】:

我有多个 csv 文件,它们由 \t (TAB) 分隔。 在每个文件中都有数据行,其左侧有一个时间线 注意:多个数据集可以有相同的时间线!没有可检测到的模式!

我想遍历所有文件,并且在每个文件中我想遍历每个标题(单词) 然后我想将标题名称(I51_RH_T)中带有(例如:I51)的数据行复制到具有相应时间线的新文件(称为I51)中! 我还想循环浏览标题的多个关键字!

这是我设法做到的:

import re, csv, os, 

keywords = ["I01", "I02", "I03"]

Input_Dir = "E:/MA/05_Sensordaten/Sensordaten txt/"
files = os.listdir(Input_Dir)

i = 0
zz = 0

for each in keywords:
    keyword = str(keywords[i])

    #print(files)
    for file in files:

        if zz <= len(files) -1:
            #print(files[zz])
            file_and_path = Input_Dir + files[zz]
            with open(file_and_path, "r") as csv_file:
                csv_reader = csv.reader(csv_file, delimiter = "\t")
                #print(csv_file)
                with open("G:/MA/05_Sensordaten/Sensordaten sortiert/Aufbau" + keyword + ".txt", "w") as new_file:
                    csv_writer = csv.writer(new_file, delimiter=" ")  # \t = TAB
                    j = 0
                    for words in csv_reader:
                        if j <= 400:
                            j += 1
                            while re.match(keyword, words[j]):
                                print(words[j])
                                j += 1
                        else:
                            break
        zz += 1
    i += 1


现在我收到列表索引超出范围的错误! 代码中缺少的是我在新文件中复制带有相应时间线的标题的部分!

我要提取数据的 csv 文件如下所示:

timeline0 I51_Rh_T I54_Rh_Rh I57_T ........
01.10.20100:00 8,47 54,67 20,54 ......
..................

欢迎任何帮助!

真诚的丹尼尔

【问题讨论】:

    标签: python csv


    【解决方案1】:
    for word in csv_reader:
        x = re.search(keyword, word) #Sucht Aufbau in csv_reader
        print(x)
    

    在这里,您将在word 中获取字典对象 您必须为该字典中的键或值再添加一个循环,例如

    for word in csv_reader:
        for key in word.keys():
            x = re.search(keyword, key) #Sucht Aufbau in csv_reader
            print(x)
    

    【讨论】:

    • 但是,如果keyword 不是一个正则表达式模式,而只是一个文字字符串,那么使用re 是没有意义的,if keyword in key: print(keyword) 就足够了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 2014-10-26
    • 1970-01-01
    • 2018-08-01
    • 2018-12-17
    • 2014-02-07
    • 2017-10-08
    • 2016-07-24
    相关资源
    最近更新 更多