Reputation: 49
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().
Upvotes: 3
Views: 134
Reputation: 11590
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)
Upvotes: 6
Reputation: 96258
If you want to read from a file, you have to open it for reading too (r
).
Upvotes: 0