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:
    print(each_line)

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?

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:
    print(foobarbazqux)

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 data.read(), or data.read(number).

You can quickly test these things out:

data_text = """\
one
two
three
"""

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

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

print(text_str)

'''result>>>
one
two
three
'''

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

print(data_list)

'''result>>>
['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()
    data_list1.append(line)

print(data_list1)

'''result>>>
['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, networking, learning, and sharing knowledge.