0
Reading files in python
b=open (a,"r") Opened the file b.read() Wrote down what's on that file But when I tried b.read() again it outputted ' ' Can someone tell me why is that?
7 ответов
+ 2
The read() function fetches the entire file content. When you open a file, the variable you assign it to, is sort of a cursor or pointer, by default pointing to the beginning of the file. Then you can proceed by:
read() read the whole content
read(n) get n bytes from file
readline() get one line at a time
As the read progresses, your file is "consumed" until reaching the end.
You can reset this file pointer to the beginning with seek(0)
https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
+ 2
Naveen K R yes, correct
+ 2
If you really want to repeat reading an open file, you can use the seek() method. For your sample it would be:
b.seek(0)
where 0 is the begin of the file. On the other hand you should try to avoid reading files repeatedly.
+ 1
To get a clear picture of what the issue is, we have to see your code in playground linked here.
+ 1
Tibor Santa brother that was very useful thank you.
0
Lothar sure I'll link it down.
Actually the problem is
When I input b.read()
It's output is the contents in the file.
But the second time I input b.read()
It outputs ' '
0
Tibor Santa so when I use read() once the cursor moves to the very end and when again I use read() it gives output from where the cursor is. Am I right?