im following along in this nifty little book and one of the coding examples just sparked my interest.

data = open('some_file.txt')
for each_line in data:

How does python know what i want it to do without really telling it?
i figured i would have to tell it how i wanted it to print the lines, like parse through each line of the file or something. But it just prints out each line. Like it knew that when i called my variable each_line it understood
so what am i missing? am i over thinking this?

Recommended Answers

All 4 Replies

In python, a file opened for reading supports the 'iterable protocol', it means that it can behave like a sequence of items, each item being a line of the file. For example it could be transformed into a list of lines

L = list(open('spam.txt'))

It can also be used in a for statement, like a list, tuple or any 'iterable'. The name of the loop variable does not have a special meaning. One could write

data = open('some_file.txt')
for foobarbazqux in data:

ok so it just autmatically reads line by line

Exactly. It reads line by line if it is used like an iterable. The other way to read is to use, or

You can quickly test these things out:

data_text = """\

# write the data text to a text file
fname = "mydata1.txt"
with open(fname, "w") as fout:

# read data back in as a text string
# the with block will close the file for you
with open(fname) as fin:
    text_str =



# read the file back in as a list (retains newline char)
with open(fname) as fin:
    data_list = fin.readlines()


['one\n', 'two\n', 'three\n']

# read the file back in as a list and remove the extra newline characters
data_list1 = []
for line in open(fname):
    line = line.strip()


['one', 'two', 'three']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.