这是一个将表格文件作为输入并将第一行作为列表返回的函数:
def firstline_to_list(fvar):
"""
Input tab separated file.
Output first row as list.
"""
import csv
lineno = 0
with open(fvar, 'r') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter='\t')
for row in tabreader:
lineno += 1
if lineno == 1:
return row
break
有没有比我这个笨重的代码更好的方法呢?
答案 0 :(得分:3)
只需在迭代器next
上调用tabreader
即可替换for循环。在python 2.7中,这应该是tabreader.next()
,而在python 3中,我认为它是next(tabreader)
。您可能还希望将try except
块中的调用包装为StopIteration
异常,以防文件为空。
所以将所有内容放在一起,这里的版本与python 2和3兼容:
def firstline_to_list(fvar):
"""
Input tab separated file.
Output first row as list.
"""
import csv, sys
with open(fvar, 'r') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter='\t')
try:
if sys.version > '3':
result = next(tabreader)
else:
result = tabreader.next()
except StopIteration:
result = None
return result
答案 1 :(得分:2)
对代码的绝对最小修改是:
def firstline_to_list(fvar):
"""
Input tab separated files.
Output first row as list.
"""
import csv
with open(fvar, 'r') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter='\t')
for row in tabreader:
return row
更好的方法是使用此处记录的Reader.next()
:https://docs.python.org/2/library/csv.html
def firstline_to_list(fvar):
"""
Input tab separated files.
Output first row as list.
"""
import csv
with open(fvar, 'r') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter='\t')
return tabreader.next()
答案 2 :(得分:2)
怎么样:
import pandas
return list(pandas.read_csv(fvar,sep='\t',nrows=1))