-1

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?

lena
  • 730
  • 2
  • 11
  • 23
  • 2
    You'd start by breaking there problem into smaller bits, then with some basic research – Mad Physicist Oct 31 '21 at 15:10
  • 1
    Please 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 Answers3

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
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
  • Why bother with numpy if you aren't going to use it's features? – Mad Physicist Oct 31 '21 at 15:13
  • 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
  • How can make float number like .00000 instead of .0 ? – lena Feb 04 '22 at 15:02
-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
  • 2
    You 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