filehandle index and len
On a filehandle (returned by the open
function) we cannot call the len
function, nor can we access arbitrary element (row) using index in a square bracket []
.
We can only use it as an iterator.
len
import sys
file = sys.argv[0]
with open(file) as fh:
print(len(fh))
Error:
Traceback (most recent call last):
File ".../fh_len.py", line 5, in <module>
print(len(fh))
~~~^^^^
TypeError: object of type '_io.TextIOWrapper' has no len()
index
import sys
file = sys.argv[0]
with open(file) as fh:
print(fh[2])
Error:
Traceback (most recent call last):
File ".../fh_index.py", line 5, in <module>
print(fh[2])
~~^^^
TypeError: '_io.TextIOWrapper' object is not subscriptable