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!
readlines
method on files is redundant with files iterator behavior; in Python 3,f.readlines()
is more verbose and no faster than (and in fact, in my tests, fractionally slower than)list(f)
, and makes people write bad code by obscuring the iterator nature of files. In reality, you rarely want to do eitherf.readlines()
orlist(f)
, because you usually want to iterate the file directly, either to process lines one at a time and discard them, or if you need alist
, you still want some preprocessing (e.g. stripping newlines and/or blank lines) that as you iterate.