How to Open a file through python

You can easily pass the file object.

with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable.

and in your function, return the list of lines

def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines 

Another trick, python file objects actually have a method to read the lines of the file. Like this:

with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).

With the second method, readlines is like your function. You don’t have to call it again.

Update
Here is how you should write your code:

First method:

def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines 
with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable (list).
    print(contents)

Second one:

with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).
    print(contents)

Hope this helps!

Leave a Comment