0

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.

5
  • 4
    why don't you pass the file name as a parameter and open the file within the function? Commented Dec 5, 2016 at 5:51
  • @Vaulstein: Because then it can't take file-likes. Commented Dec 5, 2016 at 5:54
  • @IgnacioVazquez-Abrams I have a suspicion that this won't matter to OP. Commented Dec 5, 2016 at 5:56
  • You cannot have a function call in the function definition header. Only formal parameters are allowed in the parentheses. Commented Dec 5, 2016 at 6:28
  • what @Vaulstein says might be what I need to do, mainly because once i open which ever file is specified I need to then take particular parts of it and put it into tuples Commented Dec 5, 2016 at 6:57

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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')

3 Comments

This is somewhat what i was trying to do except, I mainly wanted it to open the file in the function via the parameter and allow me to edit it
Then just send the file name as a parameter and open it in the function...
Positional parameters are file_name (1) and open-type(2)? Keyword arguments are encoding, etc.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.