views:

363

answers:

1

Python's file.read() function won't read anything. It always returns '' no matter what's inside the file. What can it be? I know it must be something straightforward, but I can't figure it out.

UPD: I tried with 'r' and 'w+' modes.

UPD: The code was:

    >>> file = open('helloworld', 'w+')
    >>> file.read()
    ''

Solution: It just came to me that, although a file is available for reading in 'w+' mode, Python truncates it after opening. 'r' (or 'r+') mode should be used instead. Thanks everyone.

+2  A: 

Caveat: I'm just guessing as to behavior that is not 'working':

If you're working in the Python interpreter,
and you do something like this:

>>> f = open('myfile.txt', 'r')
>>> f.read()

...you'll get the whole file printed to the screen.

But if you do this again:

>>> f.read()
''

...you get an empty string.

So, if you haven't already, maybe try restarting your interpreter.

From the documentation:

"To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("")."

Adam Bernier