如何仅在Python中经过某种模式后才能读取csv文件?

时间:2019-01-15 05:07:57

标签: python csv

所以我有几个表示某些数据的csv文件,每个文件可能都有不同的初始注释行

table_doi: 10.17182/hepdata.52402.v1/t7
name: Table 7
...
ABS(YRAP), < 0.1
SQRT(S) [GeV], 1960
PT [GEV], PT [GEV] LOW, PT [GEV] HIGH, D2(SIG)/DYRAP/DPT [NB/GEV]
67, 62, 72, 6.68
...
613.5, 527, 700, 1.81E-07

我也只想读入相关数据及其标头(从行开始)

PT [GEV], PT [GEV] LOW, PT [GEV] HIGH, D2(SIG)/DYRAP/DPT [NB/GEV]

因此,我想到的策略是找到模式PT [GEV]并从那里开始阅读。

但是,我不确定如何在Python中实现此目标,有人可以帮助我吗?

提前谢谢!


顺便说一句,我目前拥有的功能是

import os
import glob
import csv

def read_multicolumn_csv_files_into_dictionary(folderpath, dictionary):
    filepath = folderpath + '*.csv'
    files = sorted(glob.glob(filepath))
    for file in files:
        data_set = file.replace(folderpath, '').replace('.csv', '')
        dictionary[data_set] = {}
        with open(file, 'r') as data_file:
            data_pipe = csv.DictReader(data_file)
            dictionary[data_set]['pt'] = []
            dictionary[data_set]['sigma'] = []
            for row in data_pipe:
                dictionary[data_set]['pt'].append(float(row['PT [GEV]']))
                dictionary[data_set]['sigma'].append(float(row['D2(SIG)/DYRAP/DPT [NB/GEV]']))
    return dictionary

仅在我手动删除csv文件中的初始注释时有效。

5 个答案:

答案 0 :(得分:2)

结帐startswith。另外,您可以在此处找到详细说明。 https://cmdlinetips.com/2018/01/3-ways-to-read-a-file-and-skip-initial-comments-in-python/

答案 1 :(得分:1)

假设每个文件都有以PT [GEV]开头的行:

import os
import pandas as pd

...
csvs = []
for file in files:
    with open(file) as f:
        for i, l in enumerate(f):
            if l.startswith('PT [GEV]'):
                csvs.append(pd.read_csv(file, skiprows = i))
                break
df = pd.concat(csvs)

答案 2 :(得分:1)

在将要搜索包含PT [GEV]的行的地方尝试此操作,如果找到包含的行,它将把m更改为true并开始将剩余的日期追加到列表中:

import csv

contain= 'PT [GEV]'
List=[]
m=false
with open('Users.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=',') 
     for row in reader:
          for field in row:
              if field == contain:
              m=true
          if m==true:
             List.append(row)            

答案 3 :(得分:1)

在阅读和跳过这些行时,可以使用file.tell方法保存文件指针的位置,直到找到标题行为止,此时可以使用file.seek方法来重置文件指针返回标题行的开头,以便csv.DictReader可以将文件的其余部分解析为有效的CSV:

with open(file, 'r') as data_file:
    while True:
        position = data_file.tell()
        line = next(data_file)
        if line.count(',') == 3: # or whatever condition your header line satisfies
            data_file.seek(position) # reset file pointer to the beginning of the header line
            break
    data_pipe = csv.DictReader(data_file)
    ...

答案 4 :(得分:0)

我只需要创建一个帮助函数即可将您的csv阅读器获取第一条记录:

def remove_comments_from_file():

    file_name = "super_secret_file.csv"
    file = open(file_name, 'rU')

    csv_read_file = csv.reader(file)        

    for row in csv_read_file:
        if row[0] == "PT [GEV]"
            break

    return csv_read_file

类似的事情,当返回csv阅读器时,它将从您的第一条记录开始(在此示例中-67、62、72、6.68)