简体   繁体   中英

read in data from a text file and have each column as a list in python

Here is the data in a text file i am importing:

-2, 2.1, 0.484147876841
0, 2.4, 0.0550985751073
2, 2.5, -0.48502362586
4, 3.5, -0.161922119386
6, 4.2, 0.442947234586

I would like each column of data into a separate list, to look like:

x = [-2, 0,2 ,4 ,6]
y = [2.1, 2.4, 2.5, 3.5, 4.2]
e = [0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]

I tried the following code:

inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r')

for datapoint in inputdata:  
    datapoint=datapoint.strip('\n')
    splitdata=datapoint.split(',')
    x.append(splitdata[0])
    y.append(splitdata[1])
    e.append(splitdata[2])

What error are you receiving? Try this, it worked for me:

inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r')
x = []
y= []
e = []
for datapoint in inputdata:  
    datapoint=datapoint.strip('\n')  
    splitdata=datapoint.split(',')  
    x.append(int(splitdata[0]))  
    y.append(float(splitdata[1]))  
    e.append(float(splitdata[2]))
print x
print y
print e

Output :

[-2, 0, 2, 4, 6]
[2.1, 2.4, 2.5, 3.5, 4.2]
[0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]

Here's one way to do it:

input_file = 'data.txt'
with open(input_file) as f:
    a = [map(float, line.strip('\n').split(',')) for line in f]
    x, y, z = [list(l) for l in zip(*a)]
print(x, y, z)

Prints:

[-2.0, 0.0, 2.0, 4.0, 6.0] [2.1, 2.4, 2.5, 3.5, 4.2] [0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]

If you don't mind that x , y , and z will be tuples, you can use just zip(*a) instead of wrapping each element with a list in the last list comprehension.

First, you may need to convert to the correct datatype:

x.append(int(splitdata[0]))  
y.append(float(splitdata[1]))  
e.append(float(splitdata[2]))
...

Second, this is a csv file, and you might better process it with the right library:

import csv

with open(r"C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'rb') as csvfile:
  reader = csv.reader(csvfile):
  for row in file:
    x.append(int(row[0]))
    ...
file1=open("D:\price.txt","r")
x=[]
y=[]
z=[]
for i in file1: 
    x.append(i.strip().split())
    print(x)
for i in x:
    y.append(int(i[0]))
    z.append(int(i[1]))
print(y,z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM