0

I want to make a code to read files that contain data from a sensor. I got stuck at the start:

    import numpy as np

a = []
b = []
x = []
y = []
for line in open("YAZID.txt", "r"):
    lines = [i for i in line.split()]
    print(lines)
    a.append(float(lines[0]))
    b.append(float(lines[1]))
for i in a:
    i = float(i)
    x.append(i)
print(x)

it gives me this error

    ['0,375', '7,84E-02']
Traceback (most recent call last):
  File "c:\Users\pc orange\Desktop\graphs\graph.py", line 32, in <module>
    a.append(float(lines[0]))
ValueError: could not convert string to float: '0,375'

they get stuck at being strings

is there a way to make them into float so that i can make a plot with them the numbers are really little and i need to read the whole number each time

3
  • 2
    Do a.append(float(lines[0].replace(',','.')) Commented Aug 4, 2021 at 1:14
  • @Sujay I had already answer here. :) Commented Aug 4, 2021 at 1:15
  • @Xitiz oh! It did not update here Commented Aug 4, 2021 at 1:17

3 Answers 3

2

You can replace that , with . and then try the same thing. Here's the code:

for line in open("YAZID.txt", "r"):
    lines = [i for i in line.split()]
    print(lines)
    a.append(float(lines[0].replace(",",".")))
    b.append(float(lines[1].replace(",",".")))

Doing this should work for you.

And additionally at last you don't have to make that float again, doing just this is okay.

for i in a:
    x.append(i)
print(x)
Sign up to request clarification or add additional context in comments.

Comments

0
string= "3.141"

print(string)
print(type(string))

# converting string to float
Float = float(string)

print(Float)
print(type(Float))

Comments

0

the probleme was in my text file the comas were comas(,) not points(.) also used this code to make them into float

 x = [float(c) for c in a]

thanks everyone for your help

2 Comments

But your error is in a.append(float(lines[0].replace(",","."))) so this is not technically an answer! And if you follow my answer while appending in a then you don't have to do this as well. I had mentioned that too in my answer! I had already answered your full questions, I don't think you have to write a new answer, you can accept my answer and it is officially your problem solution!
i am quite new in here so i am stiill not accustumed to how it works here i used your answer and it did the job thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.