0

I already looked into many answers but none helped me. I need a code that if the file does not exist then create and then open for reading and writing. The code is writing but not reading, what is the problem?

>>> `file = open('test.txt', 'w+')`
>>>  file.write('this is a test')
14
>>>  file.read()
''
>>>

1 Answer 1

2

You have to seek to the beginning of the file before attempting to read it.

>>> _file = open('test.txt', 'w+')
>>> _file.write('this is a test')
14
>>> _file.read()
''
>>> _file.seek(0)
0
>>> _file.read()
'this is a test'
>>> 

0 indicates the beginning of the file. You can get the current position by calling _file.tell() You could programatically combine _file.tell with _file.seek(offset, fromwhat).

Also, it is bad practice to use builtin's(file) as variable names.

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

Comments

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.