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

use*_*646 -3 python parsing file

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

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

我怎样才能做到这一点?

nos*_*klo 13

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)
Run Code Online (Sandbox Code Playgroud)


Sov*_*iut 5

您使用什么类型的分隔符?也就是说,是什么将您的列分开?

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

col1,  col2,  col3
col11, col12, col13
col21, col22, col23
col31, col32, col33
Run Code Online (Sandbox Code Playgroud)

以下代码将解析它并打印每行的第一列和最后一列:

# 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
Run Code Online (Sandbox Code Playgroud)


Dzi*_*inX 5

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

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
Run Code Online (Sandbox Code Playgroud)

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

Edgar; Alan; Poe
John; Smith

Lots;   of;   whitespace; here
Run Code Online (Sandbox Code Playgroud)

它将产生以下输出:

('Edgar', 'Poe')
('John', 'Smith')
('Lots', 'here')
Run Code Online (Sandbox Code Playgroud)

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