Home > database >  Convert int value in txt file to float
Convert int value in txt file to float

Time:11-01

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?

CodePudding user response:

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]))

CodePudding user response:

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))   ",") 

CodePudding user response:

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(",")))
  • Related