Define a function to pass filename to make opening of files easier?

Hello everyone! I’m kinda new to Python and still learning, i have tried to search for solutions to my problem but everything i’ve tried so far has failed with different results and i finally decided that i had to give up and just ask. Sorry if it’s all too obvious :smiley: I’m playing around with opening and reading some txt files and looping trough them, and this works exactly as intended:

with open("/path/to/folder/file1.txt") as lines:
    for line in lines:

But i was thinking if i could make this process less repetitive by somehow store the “/path/to/folder” in a variable and then pass the filename itself with a function, but my tries so far have failed pretty big :crazy_face:

txt_file_folder = "/path/to/folder/"

def txt_file(file):
    with open (txt_file_folder + file) as lines:
        for line in lines:

and then try to use it like this:


But from the error-messages i’ve got so far i can tell that it’s not really meant to use function-arguments like this. I have tried to convert it using str() and other methods i could think of but i still have no idea, maybe i’m looking for an impossible solution? I have been thinking about using format-strings to replace {filename} in the path above too somehow, but i’m not really sure it will be any less manual work than to just do it like my first example on all of the files. Hope anyone can lead me in the right direction or tell me what to search for, thanks :slight_smile:

There’s no reason that couldn’t work. But you haven’t shown the error, so it’s hard to know what might be wrong.

That said, I’d normally prefer to use pathlib Path instead of just raw strings. But the raw strings could work as well.

from pathlib import Path

txt_file_folder = Path("/path/to/folder")

def txt_file(file):
    with open (txt_file_folder / file) as lines:
        for line in lines:



Your code looks fine. Without knowing what error message you got, we
have to guess what it is.

My guess is that you are writing this:


and then get a NameError:

NameError: name 'file1' is not defined

You need to put the file name in quotes to make it a string, otherwise
Python will treat it as a variable called file1, which is not defined.

1 Like

Big thanks to both of you for your answers! I tried to put “file1.txt” in a string in two ways yesterday, (both by adding qoutes around, and by str(), but apperently i was too tired. Today it worked like a charm and the reason i was sure it was some error with the way i used the function was that the error-message said something about “Can’t convert function to str”. But the problem solution ended up being as you both suggested, qoutes around the filename, and that i actually missed to give it another parameter since i runned this function inside another function.

Also @BowlOfRed thank you for the tip about pathlib, will check that out later!