将txt文件中的int值转换为float

Convert int value in txt file to float

我有这样的 txt 文件 f1= 255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,0,0,0,0,0,255,219,0 我需要将这些数字转换为浮点数并保存在 f2 中(f2 包含转换后的浮点值)该怎么做?

假设输入正确,使用列表理解:

with open(file_path, "r") as f_r:
    num_strs = f_r.read().split(",")
    num_floats = [float(x) for x in num_strs]

如果您想将输出写入文件:

separator = ","
with open(file_path, "w") as f_w:
    f_w.write(separator.join([str(x) for x in num_floats]))

这会将浮点数的默认字符串表示形式写入文件 如果您还想格式化浮点数(例如设置精度):

separator = ","
with open(file_path, "w") as f_w:
    f_w.write(separator.join([f"{x:.2f}" for x in num_floats]))

我写了一行: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(",")))
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)) + ",")