从txt文件将数据导入Python

时间:2017-05-02 13:29:38

标签: python list import python-import genfromtxt

我有一个.txt文件,其数据排列如下:

3430 4735 1
3430 4736 1
3430 4941 2
3430 5072 1
3430 5095 1
3430 5230 1
3430 5299 1
3430 5386 1
3430 5552 1
3430 5555 1
3430 5808 1
3430 5853 1
3430 5896 1
3430 5988 1
3430 6190 4
3430 6191 1
3430 6225 1
3430 6296 1

如何从中创建Python列表,一个包含第一列中的数字,另一个包含第二列中的数字?

4 个答案:

答案 0 :(得分:1)

看看pandas库,它对数据流非常有用。 http://pandas.pydata.org/

或者你可以直接这样做:

list1 = []
list2 = []
list3 = []
with open('test.txt', 'r') as f:
    content = f.readlines()
    for x in content:
        row = x.split()
        list1.append(int(row[0]))
        list2.append(int(row[1]))
        list3.append(int(row[2]))

答案 1 :(得分:0)

one_list = []
another_list = []
with open("somefile.txt", "r") as this_file:
    for line in this_file:
        one_list.append(line.split(' ')[0])
        another_list.append(line.split(' ')[1])

将文件中每行的第一个元素放入一个列表,将所有第二个元素放入另一个列表中。

答案 2 :(得分:0)

这样的东西?

flst = []
slst = []
tlst = []

file = open('your.txt', 'r')
for line in file:
    a = line.split()
    flst.append(int(a[0]))
    slst.append(int(a[1]))
    tlst.append(int(a[2]))

创建三个空列表,打开文件并读取txt文件的每一行。然后拆分行,并将第一,第二和第三个字符串的每一行添加到相应的列表中。

答案 3 :(得分:0)

list1 = []

list2 = []
whith open('a.txt','r') as fh:
  lineList = fh.readlines()
  for line in listList:
    numbers = line.strip().split()
    list1.appned(numbers[0])
    list2.extend(numbers[1:])

print(list1)
print(list2)