I have txt file like this f1= 255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,0,0,0,0,0,255,219,0
I need to convert these numbers to float and save in f2( f2 contain the converted float values) how can do that?
Asked
Active
Viewed 424 times
-1

lena
- 730
- 2
- 11
- 23
-
2You'd start by breaking there problem into smaller bits, then with some basic research – Mad Physicist Oct 31 '21 at 15:10
-
1Please provide a [mcve] after reading [ask]. If you want text output, the file already contains valid floats as far as python is concerned. Otherwise you need to be much more specific – Mad Physicist Oct 31 '21 at 15:14
-
So, just to be clear, do you expect the output in f2 to be `255.0,216.0,...`? – joanis Oct 31 '21 at 15:29
3 Answers
0
Assuming input is correct, using list comprehension:
with open(file_path, "r") as f_r:
num_strs = f_r.read().split(",")
num_floats = [float(x) for x in num_strs]
And if you want to write the output in a file:
separator = ","
with open(file_path, "w") as f_w:
f_w.write(separator.join([str(x) for x in num_floats]))
This will write the default string representation of floats to file If you want also to format the floats (set precision for example):
separator = ","
with open(file_path, "w") as f_w:
f_w.write(separator.join([f"{x:.2f}" for x in num_floats]))

user107511
- 772
- 3
- 23
-
-
-
-
@oleva just change the separator to a new line in both split and join – user107511 Feb 05 '22 at 21:00
0
import numpy as np
numbers = np.loadtxt("file.txt", delimiter=",")
#It should parse it as float64 already, but just in case:
numbers=np.float64(numbers)
with open("file2.txt", "w") as txt_file:
for number in numbers:
txt_file.write("".join(str(number)) + ",")

Toby
- 86
- 3
-
-
He said he needed it in a "float array" for the intermediate part, which I assumed by "array" he meant "np.array". He edited the question just now. Look at the question history. – Toby Oct 31 '21 at 15:15
-
-1
I wrote a one-liner :D
import pathlib
# Read the text file, split it by commas, then convert all items to floats
output = list(map(float, pathlib.Path("file.txt").read_text().split(",")))

Bharel
- 23,672
- 5
- 40
- 80
-
2You also appear to have missed a major part of the question. Please add prose in addition to a code dump if you believe this answers the question. – Mad Physicist Oct 31 '21 at 15:11
-
@MadPhysicist The OP seems to have modified his original question and changed his output requirements. – Bharel Oct 31 '21 at 17:36