我有一个文本文件(tab delimeted),我想使用list comprehension在列表(list1)中传递字段1,在另一个列表(list2)中传递字段3。
我写的代码是:
with open (path) as file1:
list1 = [line.strip().split('\t')[0] for line in file1];
list2 = [line.strip().split('\t')[3] for line in file1];
问题是list2保持为空。
有没有想过为什么会这样?
谢谢!
答案 0 :(得分:1)
您需要将pointet重置回文件的开头:
with open (path) as file1:
list1 = [line.strip().split('\t')[0] for line in file1]
file1.seek(0)
list2 = [line.strip().split('\t')[3] for line in file1];
但是你可以在一次传递中完成它,只需在迭代时附加到每个传递,所以你只需要翻阅一次文件内容:
with open (path) as file1:
list1, list2 = [], []
for line in file1:
spl =line.strip().split('\t')
list1.append(spl[0])
list2.append(spl[3])
您还可以使用csv lib为您解析数据:
import csv
with open (path) as file1:
list1, list2 = [], []
for row in csv.reader(file1, delimiter="\t):
list1.append(row[0])
list2.append(row[3])