It's my first time starting Python, but after I type(), I can't print() properly.

Asked 2 years ago, Updated 2 years ago, 16 views

After one type() in the middle, the value does not appear in the last print (diary).

If you try f.seek(0), you get the same result.

I wonder why this is happening.

Thank you.

python

2022-09-20 19:02

1 Answers

The read() method in the file reads all the text in the file and returns it as a string if nothing is specified by the argument.

In type(f.read(), f.read() inside got all the text as a string and put it in type() so <class 'str'> was output.

Since then, diary=f.read() has been re-run, but I can't read any more because I've already read all the text in the file before. Therefore, f.read() returns an empty string ' and print(diary) outputs an empty string, which outputs one white blank line on the screen.

And f.If you use see(0), you must use it before f.read() again, as shown below.

f=open('a.txt','r')
type(f.read())
f.seek(0)
diary=f.read()
print(diary)

-Result


2022-09-20 19:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.