Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I am very new to programming and the python language.

I know how to open a file in python, but the question is how can I open the file as a parameter of a function?

example:

function(parameter)

Here is how I have written out the code:

def function(file): 

with open('file.txt', 'r') as f: 

contents = f.readlines() 

lines = [] 

for line in f: 

lines.append(line) 

print(contents)

1 Answer

0 votes
by (106k points)

You can easily pass the file object.

with open('file.txt', 'r') as f: 

contents = function(f) 

and in your function, return the list of lines

def function(file): 

lines = [] 

for line in f: 

lines.append(line) 

return lines

To know more about this you can have a look at the following video tutorial:-


 

Browse Categories

...