Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file variable - what is it?

I just started with Python, and since my background is in more low-level languages (java, C++), i just cant really get some things.

So, in python one can create a file variable, by opening a text file, for example, and then iterate through its lines like this:

f = open(sys.argv[1])
for line in f:
    #do something

However, if i try f[0] the interpreter gives an error. So what structure does f object have and how do i know in general, if i can apply for ... in ... : loop to an object?

like image 371
coffee Avatar asked Dec 02 '22 23:12

coffee


1 Answers

f is a file object. The documentation lists its structure, so I'll only explain a the indexing/iterating behavior.

An object is indexable only if it implements __getitem__, which you can check by calling hasattr(f, '__getitem__') or just calling f[0] and seeing if it throws an error. In fact, that's exactly what your error message tells you:

TypeError: 'file' object has no attribute '__getitem__'

File objects are not indexable. You can call f.readlines() and return a list of lines, which itself is indexable.

Objects that implement __iter__ are iterable with the for ... in ... syntax. Now there are actually two types of iterable objects: container objects and iterator objects. Iterator objects implement two methods: __iter__ and __next__. Container objects implement only __iter__ and return an iterator object, which is actually what you're iterating over. File objects are their own iterators, as they implement both methods.

If you want to get the next item in an iterable, you can use the next() function:

first_line = next(f)
second_line = next(f)
next_line_that_starts_with_0 = next(line for line in f if line.startswith('0'))

One word of caution: iterables generally aren't "rewindable", so once you progress through the iterable, you can't really go back. To "rewind" a file object, you can use f.seek(0), which will set the current position back to the beginning of the file.

like image 70
Blender Avatar answered Dec 09 '22 14:12

Blender