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?

11th Feb 2020, 6:28 AM
Naveen K R
7 Réponses
+ 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
11th Feb 2020, 6:39 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Naveen K R yes, correct
11th Feb 2020, 6:47 AM
Tibor Santa
Tibor Santa - avatar
+ 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.
11th Feb 2020, 12:08 PM
Lothar
Lothar - avatar
+ 1
To get a clear picture of what the issue is, we have to see your code in playground linked here.
11th Feb 2020, 6:32 AM
Lothar
Lothar - avatar
+ 1
Tibor Santa brother that was very useful thank you.
11th Feb 2020, 6:53 AM
Naveen K R
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 ' '
11th Feb 2020, 6:36 AM
Naveen K R
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?
11th Feb 2020, 6:44 AM
Naveen K R