# 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
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
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)
您使用哪种分隔符?也就是说,是什么分隔了你的列?
我假设您使用逗号分隔符,如下所示:
以下代码将对其进行分析并打印每行的第一列和最后一列:
解析写入文本文件的表最方便的方法是使用csv module。它支持任何分隔符,使用起来比手动逐行解析更方便。示例:
现在,如果你给它一个这样的文件:
它将产生以下输出:
编辑:到
csv.reader
的自定义参数也可以作为关键字参数传递(谢谢,nosklo!)。csv模块是更简单的方法。 您可以对以下代码使用任何分隔符:
相关问题 更多 >
编程相关推荐