user3500017
user3500017

Reputation: 197

Python - Open Read/Write Error

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

Upvotes: 0

Views: 563

Answers (1)

Saimadhav Heblikar
Saimadhav Heblikar

Reputation: 712

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.

Upvotes: 2

Related Questions