简体   繁体   中英

How could I open a file via the function parameter in python?

I'm trying to open a file via a function's parameter. The function I'm trying to make is going to be a multi-purpose one that will work with different files.

def word_editor(open(filename, 'f'))

Would this be the correct way to open it? filename will represent whatever file I am opening.

Defining any function you should list the arguments' names only. That's why your line def word_editor(open(filename, 'f')) can't be correct. If you want to work with file like objects, you should pass it as an argument like this:

def word_editor(fl):
    text = fl.read()
    print(text)

After that you can use this function like this:

f1 = open("file1.txt", "r")
word_editor(f1)
f1.close()

with open("file2.txt", "r") as f2:
    word_editor(f2)

I think you want this.

def test(file_object):
     for line in file_object:
         print(line) 

test(open('test.txt','r'))

Output:

line #1
line #2
....  
....
line #n 

Alternatively, you can pass filename as a parameter of the function, like below:

def test(file_name):
    with open(file_name,'a+') as f:  
         # do whatever you want to do. 

test('your_file.txt')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM