Python file variable - what is it? -


i started python, , since background in more low-level languages (java, c++), cant things.

so, in python 1 can create file variable, opening text file, example, , iterate through lines this:

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

however, if try f[0] interpreter gives error. structure f object have , how know in general, if can apply for ... in ... : loop object?

f file object. documentation lists structure, i'll explain indexing/iterating behavior.

an object indexable if implements __getitem__, can check calling hasattr(f, '__getitem__') or calling f[0] , seeing if throws error. in fact, that's error message tells you:

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

file objects not indexable. can call f.readlines() , return list of lines, indexable.

objects implement __iter__ iterable for ... in ... syntax. there 2 types of iterable objects: container objects , iterator objects. iterator objects implement 2 methods: __iter__ , __next__. container objects implement __iter__ , return iterator object, you're iterating over. file objects own iterators, implement both methods.

if want next item in iterable, can use next() function:

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

one word of caution: iterables aren't "rewindable", once progress through iterable, can't go back. "rewind" file object, can use f.seek(0), set current position beginning of file.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -