我有一个文本文件(制表符),我想使用列表推导在列表(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 保持为空。
有什么想法为什么会这样吗?
谢谢!
您需要
将点数重置回文件的开头:
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 库为您解析数据:
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])