Reputation: 3
I have a text file that consists of 1 column of numbers (like: 1e-5, 1.15e3, etc). How do I save the column to a list as just floats?
input text file looks like this:
1.00E-05
1.06E-05
1.13E-05
1.19E-05
I tried this:
file=open('C:\Users\Enrique Jr\Desktop\h_energy.txt', "r")
h_energy=[]
for line in file:
h_energy.append((line.split()))
file.close()
and got an output of this:
[['1.00E-05'], ['1.06E-05'], ['1.13E-05'], ['1.19E-05']
Upvotes: 0
Views: 304
Reputation: 3360
try this:
file=open('output.txt', "r")
array = []
for line in file:
array.append(float(line.rstrip()))
file.close()
Upvotes: 0
Reputation: 7
file=open('output.txt', "r")
for line in file:
list.append(float(line.split("\t")[0]))
list.append(float(line.split("\t")[1]))
file.close()
If you require ints and floats to be stored as different types and not just have float representation of integers, then you would need to try-catch to see if you can parse as an int, and if not then as a float:
try:
list.append(int(line.split("\t")[0]))
except ValueError:
try:
inNumberfloat = float(inNumber)
list.append(float(line.split("\t")[0]))
except ValueError:
#neither an int nor float
Upvotes: 0
Reputation: 40624
You can use the csv reader library in python: https://docs.python.org/2/library/csv.html
It will be something like this:
>>> import csv
>>> with open('output.txt', 'r') as csvfile:
... data = csv.reader(csvfile, delimiter='\t')
... print data
[["1", "2"], ["3.4", "5"], ...]
You will need to convert the data from text to float or int yourself.
Upvotes: 3