Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there pythonic oneliner to iterate over lines of a file?

Tags:

python

file

90% of the time when I read file, it ends up like this:

with open('file.txt') as f:
    for line in f:
        my_function(line)

This seems to be a very common scenario, so I thought of a shorter way, but is this safe? I mean will the file be closed correctly or do you see any other problems with this approach? :

for line in open('file.txt'):
    my_function(line)

Edit: Thanks Eric, this seems to be best solution. Hopefully I don't turn this into discussion with this, but what do you think of this approach for the case when we want to use line in several operations (not just as argument for my_function):

def line_generator(filename):
    with open(filename) as f:
        for line in f:
            yield line

and then using:

for line in line_generator('groceries.txt'):
    print line
    grocery_list += [line]

Does this function have disadvantages over iterate_over_file?

like image 665
user1308345 Avatar asked Feb 05 '23 00:02

user1308345


1 Answers

If you need this often, you could always define :

def iterate_over_file(filename, func):
    with open(filename) as f:
        for line in f:
            func(line)


def my_function(line):
    print line,

Your pythonic one-liner is now :

iterate_over_file('file.txt', my_function)
like image 97
Eric Duminil Avatar answered Feb 08 '23 15:02

Eric Duminil