Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python csv模块从标头读取数据_Python_Csv - Fatal编程技术网

python csv模块从标头读取数据

python csv模块从标头读取数据,python,csv,Python,Csv,我有以下格式的文件 # Data set number 1 # # Number of lines 4010 # Max number of column 3 is 5 # Blahblah # More blahblah 1 2 1 110 2 2 5 20 21 465 417 38 2 1 2 33 46 17 ...... 4010 3 5 1001 2010 3355 107 2039 # Data set number 2 # # Number of lines 4010 #

我有以下格式的文件

# Data set number 1 
#
# Number of lines 4010
# Max number of column 3 is 5
# Blahblah
# More blahblah
1 2 1 110 
2 2 5 20 21 465 417 38
2 1 2 33 46 17
......
4010 3 5 1001 2010 3355 107 2039
# Data set number 2 
#
# Number of lines 4010
# Max number of column 3 is 5
# Blahblah
# More blahblah
1 2 1 110 
2 2 5 20 21 465 417 38
2 1 2 33 46 17
......
我希望读取数据集的数量、行的数量和第3列的最大数量。我搜索并发现csv模块可以读取标题,但我可以读取标题的编号并存储吗?我所做的是

nnn = linecache.getline(filename, 1)
nnnn = nnn(line.split()[4])
number = linecache.getline(filename, 3)
number2 = number(line.split()[4])
mmm = linecache.getline(filename, 5)
mmmm = mmm(line.split()[7])
mmmmm = int(mmmm)
max_nb = range(mmmmm)
n_data = int(nnnn)
n_frame = range(n_data)
singleframe = natoms + 6

像这样。如何读取这些数字并使用csv模块存储?我使用“singleframe”跳过了6条标题行,但也很好奇csv模块如何读取6条标题行。谢谢

您没有真正的CSV文件;您使用的是专有格式。直接解析即可,使用正则表达式快速提取所需数据:

import re

set_number = re.compile(r'Data set number (\d+)'),
patterns = {
    'line_count': re.compile(r'Number of lines (\d+)'),
    'max_num': re.compile(r'Max number of column 3 is (\d+)'),
}

with open(filename, 'r') as infh:
    results = {}
    set_numbers = []

    for line in infh:
        if not line.startswith('#'):
            # skip lines without a comment
            continue

        set_match = set_number.match(line)
        if set_match:
            set_numbers.append(int(set_match.group(1)))
        else:
            for name, pattern in patterns.items():
                match = pattern.search(line)
                if match:
                    results[name] = int(match.group(1))

请勿使用linecache模块。它将把整个文件读入内存,实际上只用于访问Python源文件;每当需要打印回溯时,此模块将缓存与当前堆栈相关的源文件。您只能在需要随机行的较小文件中重复使用它。

此处不需要csv不确定您希望linecache在此处为您做什么;这是一个Python源代码内省工具,不是一个通用软件包。@njzk2 Hmm他们只使用linecache,行拆分就可以了?@MartijnPieters我使用linecache的原因是读取特定的X行标题行。感谢您对linecache的建议。在我的文件中,我的数据集编号将是数组,但行数和第3列的最大编号是单个数字。我如何储存这个?就像'nlines=4010'@user1798797:您的意思是需要读取所有数据集行吗?@user1798797:代码现在将读取所有数据集编号,并将它们收集到一个列表中。我希望获得n_Data=2390,因为我的文件中有2390个'Data set',并获得n_line=4010。我可以使用ary=rangen_数据生成数组,但我只希望将这些数据数、行数存储到单个数组中name@user1798797:对不起,我不太明白。也许您可以用预期的输出更新您的问题?