I have a file in which values are in scientific notation 3.198304894802781462e+00 . I want to convert these in integers. I have tried this:
data = [int(float(number))
for line in open('data.txt', 'r')
for number in line.split()]
Error:
could not convert string to int: '1.874475383557408747e+01,3.627623082212955374e+00,9.037237691778705084
you can use the context manager to read from your file:
data = []
with open('data.txt', 'r') as fp:
for line in fp.readlines():
for number in line.split(','):
data.append(int(float(number.strip())))
if you want to append the data list to your file:
with open('data.txt', 'a') as fp:
fp.write(",".join(str(e) for e in data))
Judging by your error message, your numbers are delimited by ,
, not whitespace. You must therefore use line.split(',')
instead.
with open('data.txt', 'r') as in_stream:
data = [
int(float(number))
for line in in_stream
for number in line.split(',')
]
try something like this. you need to split the string and then apply the float function on every item:
a = '1.874475383557408747e+01,3.627623082212955374e+00,9.037237691778705084'
b = a.split(',')
print(b)
for n in b:
print(float(n))
or simply:
res = [float(n) for n in a.split(',')]
I assumed that you have your data as string but from your example this should work:
data = [int(float(number))
for line in open('data.txt', 'r')
for number in line.split(',')]
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.