用Python解析包含列数据的文件

2024-05-09 08:46:15 发布

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

我有一个以行和列的形式包含符号表details.Its的文件。

我需要提取第一列和最后一列。

我该怎么做?


Tags: 文件details形式its符号表
3条回答

您使用哪种分隔符?也就是说,是什么分隔了你的列?

我假设您使用逗号分隔符,如下所示:

col1,  col2,  col3
col11, col12, col13
col21, col22, col23
col31, col32, col33

以下代码将对其进行分析并打印每行的第一列和最后一列:

# open file to read
f = file('db.txt', 'r')

# iterate over the lines in the file
for line in f:
    # split the line into a list of column values
    columns = line.split(',')
    # clean any whitespace off the items
    columns = [col.strip() for col in columns]

    # ensure the column has at least one value before printing
    if columns:
        print "first", columns[0]  # print the first column
        print "last", columns[-1] # print the last column

解析写入文本文件的表最方便的方法是使用csv module。它支持任何分隔符,使用起来比手动逐行解析更方便。示例:

import csv

def get_first_and_last_column(filename, separator):
    with file(filename, 'rb') as file_obj:
        for line in csv.reader(file_obj, 
              delimiter=separator,    # Your custom delimiter.
              skipinitialspace=True): # Strips whitespace after delimiter.
            if line: # Make sure there's at least one entry.
                yield line[0], line[-1]

if __name__ == '__main__':
    for pair in get_first_and_last_column(r'c:\temp\file.txt', ';'):
        print pair

现在,如果你给它一个这样的文件:

Edgar; Alan; Poe
John; Smith

Lots;   of;   whitespace; here

它将产生以下输出:

('Edgar', 'Poe')
('John', 'Smith')
('Lots', 'here')

编辑:到csv.reader的自定义参数也可以作为关键字参数传递(谢谢,nosklo!)。

csv模块是更简单的方法。 您可以对以下代码使用任何分隔符:

import csv

def import_text(filename, separator):
    for line in csv.reader(open(filename), delimiter=separator, 
                           skipinitialspace=True):
        if line:
            yield line

for data in import_text('somefile.txt', '/'):
    print (data)

相关问题 更多 >