2

Here's the python(3.4) code:

test = open('test.txt', 'r+')
test.truncate();
i = 0
stop = 99

while i <= stop:
    test.write("{:0>{}}|".format(i, len(str(stop))))
    i += 1

print(test.read())

It writes the file just fine, but it won't print it for some reason.

test = open('test.txt', 'r+')

print(test.read())

This prints it as expected, so I don't know where the issue may be.

Update:

Using seek(0) solved it. Can you link an explanation about it, please? I can't find it in the language's documentation.

Fábio Queluci
  • 311
  • 1
  • 2
  • 15
  • 1
    The file pointer is at the end of the file after you write to it, so there's nothing to `read()`. Possibly relevant: http://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file/14276108#14276108 – Wooble May 16 '14 at 23:18
  • The docs you're looking for are that of the `io` module. Specifically, file-like objects inherit from `IOBase`; [here is the docs on seek](https://docs.python.org/2/library/io.html#io.IOBase.seek) – roippi May 17 '14 at 03:16

2 Answers2

6

Files objects point to a particular place in the file. After writing all of that stuff, your file object points to the end of the file. Reading from that point gets nothing, as expected.

test.seek(0)
print(test.read())

will read from the beginning.

Edit: a diagram. You open the file, it contains nothing.

''
 ^

you write some things to the file.

'hello, world\n'
               ^

Every time you write to the file, more stuff gets added where it's pointing.

'hello, world\nokay, goodbye!'
                             ^

Now you read the file all the way to the end!

''

It prints nothing because you started reading from the end. seek tells us to point someplace else in the file. Since we want to read all of it, we should start at position 0.

> seek(0)
'hello, world\nokay, goodbye!'
 ^

Reading from the beginning reads everything.

hello, world
okay, goodbye!
U2EF1
  • 12,907
  • 3
  • 35
  • 37
1

try to "rewind" the file pointer using test.seek(0) before the read

Pavel
  • 7,436
  • 2
  • 29
  • 42