我想打开一个.txt文件进行读写,将其内容保存到一个变量中,然后将该变量转换为float类型。当把str类型的变量转换为float类型时,我收到一个ValueError。【替换代码0
file = open("my_file.txt", "r+")
value = file.read()
float_value = float(value)
我的理解是,如果.txt是空的,我就会收到这个错误。如果.txt包含一个数字并且使用了 "r "就不会出现错误。然而,我想读写该文件,如果我使用w+或r+,就会自动擦除.txt,从而无法进行转换。
我怎样才能打开文件进行读写,使其不擦除.txt的内容?
我在一个类似的主题中发现了这个问题,并尝试了以下解决方案,但它对我不起作用。
with open('my_file.txt', 'w+') as file:
file.seek(0)
value = file.read()
float_value = float(value)
我暂时解决了这个问题,在.txt中以0开头,然后。
Opening the file in 'r'
Storing the value in a variable
Converting the stored str value into a float
Closing the file
再次打开文件,但这次是以'w'的形式(.txt被抹去了,但我的值已经存储在一个浮动变量中)。
Performing any calculations to the float variable.
Converting the new value to a str type.
Writing the new value as str to .txt
我希望r+或w+能让我执行这些操作,而不必两次打开和关闭文件。如果我找到一个更简单的解决方案,我将进行第二次更新。
这里是临时解决方案。
file = open("my_file.txt", "r")
value = file.read()
float_value = float(value)
file.close()
new_number = 5.5
file = open("my_file.txt", "w")
new_value = float_value + new_number
str_value = str(new_value)
file.write(str_value)
file.close()
UPDATE2:
我收到了一个有效的解决方案,它在下面的评论中标明。