Fábio Queluci
Fábio Queluci

Reputation: 311

Can't print file

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.

Upvotes: 2

Views: 1566

Answers (2)

U2EF1
U2EF1

Reputation: 13279

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!

Upvotes: 6

Pavel
Pavel

Reputation: 7562

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

Upvotes: 1

Related Questions