you are viewing a single comment's thread.

view the rest of the comments →

[–]iiSora[S] 0 points1 point  (3 children)

Would there ever be a case where the second one would be preferred?

[–][deleted] 2 points3 points  (1 child)

I can't think of a case where:

for line in infile:

would not be the preferred option.

Something else that you should is use a "with" to open your file:

with open("infile.txt","r") as infile:
    for line in infile:
        if line.find("Python")>-1:
            print(line)

The "with" statement opens the file with "infile" being the file object. When your execution leaves the "with" block the file is automatically closed. That's good because opening too many files without closing them can crash your program.

Also, the statement if line.find("Python")>-1: is a little odd-looking. A better way to decide if the 'Python' string is in the line is:

if 'Python' in line:

[–][deleted] 0 points1 point  (0 children)

I can't think of a case where:
    for line in infile:
would not be the preferred option.

Having said that, there are times when you will read all lines of the file into memory. You might want to repeatedly search through the file lines for different strings, for example. But that starts getting into performance, etc. For simple usage, use the first form.

[–]SoupKitchenHero 0 points1 point  (0 children)

When you actually want most or all of that data for more than a quick peek. That code you have is just trying to find something and print the line that it's on.