Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Open a file through python

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)    
like image 833
user2891763 Avatar asked Oct 22 '13 03:10

user2891763


1 Answers

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!

like image 82
aIKid Avatar answered Oct 01 '22 13:10

aIKid