根据特定标准将文本文件读入列表

2024-09-28 20:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下内容的文本文件:

str1 str2 str3 str4
0        1    12     34
0        2      4     6
0        3     5      22
0       56    2      18
0         3    99    12    
0         8    5       7      
1       66    78    9

我想把上面的文本文件读入一个列表,这样程序就可以从第一列值大于零的行开始读取。你知道吗

如何在python3.5中实现它?你知道吗

我尝试了genfromtxt(),但只能跳过顶部固定数量的行。因为我要读不同的文件,所以我需要别的东西。你知道吗


Tags: 文件程序列表数量文本文件str1str2genfromtxt
2条回答
lst = []
flag = 0 

with open('a.txt') as f:
    for line in f:
        try:
            if float(line.split()[0].strip('.')) >0:
                flag = 1 
            if flag == 1:
                lst += [float(i.strip('.')) for i in line.split()]
        except: 
            pass

这是csv模块的一种方法。你知道吗

import csv
from io import StringIO

mystr = StringIO("""\
str1 str2 str3 str4
0        1    12     34
0        2      4     6
0        3     5      22
0       56    2      18
0         3    99    12    
0         8    5       7      
1       66    78    9
2       50    45    4
""")

res = []

# replace mystr with open('file.csv', 'r')
with mystr as f:
    reader = csv.reader(mystr, delimiter=' ', skipinitialspace=True)
    next(reader)  # skip header
    for line in reader:
        row = list(map(int, filter(None, line)))  # convert to integers
        if row[0] > 0:  # apply condition
            res.append(row)

print(res)

[[1, 66, 78, 9], [2, 50, 45, 4]]

相关问题 更多 >