3

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().

3
  • Debugging 101: Have you checked what record is? Commented Oct 11, 2015 at 14:04
  • There is nothing in record when I do print() although I'm reading from a file which has a number in it Commented Oct 11, 2015 at 14:05
  • @MasaTono, what are you actually trying to do? Commented Oct 11, 2015 at 14:12

2 Answers 2

6

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)

Sign up to request clarification or add additional context in comments.

3 Comments

plus 1 for explaining what is actually causing the issue
Worth pointing out that w+ is only really useful if you want to seek back and read after writing. It will always truncate so there will be nothing to read unless you write
@PadraicCunningham done, thank you for the suggestion
0

If you want to read from a file, you have to open it for reading too (r).

4 Comments

But I though that w+ opens it for writing and reading if I read correctly from websites
@MasaTono, r+ is for reading and writing, if you want to add data use a
w+: Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.
What Pynchia said. See stackoverflow.com/a/1466036/4014959 for descriptions of all the (standard) file modes that Python inherits from C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.