Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Reading numbers from text file

Tags:

python

file

I know this is a simple question, but I am extremely stuck.

file=open("record.txt","w+")
record = file.read()
print("The record is "+str(record)+"!!")

main code... 
file.write(str(reaction)) 
file.close()

I have got his code and I've got a number of 0.433534145355 in the file, but when I do the command of print the +str(record)+, it only comes up with The record is !! and the number is not there. What is wrong with this code. Is there a special code with decimal places, and I do not want to use int().

like image 375
Masa Tono Avatar asked May 10 '26 13:05

Masa Tono


1 Answers

As it says here:

'w+' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

so yes, your file is also opened for reading, but it is truncated (i.e. it is now zero bytes long, it's empty), leaving nothing left to read of what was there already.

Essentially, the w in 'w+' means the mode is orientated to writing, giving you the option to read as well (useful in those cases when you need to seek back and read what you have written. There will be nothing to read unless you write)

Instead you can use:

'r+' Open for reading and writing. The stream is positioned at the beginning of the file.

In this case, the r in 'r+' signifies the mode is orientated to reading, giving you the option to seek and write where necessary (useful when data is present already, but might need to be changed)

like image 137
Pynchia Avatar answered May 12 '26 03:05

Pynchia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!