Home > Software engineering >  how to open a file by passing a variable name which contains the directory where the file is located
how to open a file by passing a variable name which contains the directory where the file is located

Time:03-09

I'm working on a function where I need to open a file e.g. "hello.txt" by passing a variable name that contains a directory of where the file is located instead of the file name. Below is a dummy code that I have designed for this. In short I need to be able to open a file which is located in that directory by passing a directory name as you can see in updated.

def folder_things():
path = 'C:\\Users\\blazh\\Documents\\Vladyslav\\City-Project\\Python\\'
folder_code = "518Z%"
updated = path   folder_code
cwd = os.listdir(updated)
print("You have:", cwd)

st = ""
for x in cwd:
    st  = x

print(st)

# BECOMES A STRING
str(st)
print(type(st))
print(st)
final = ("'" st "'")
f = open(st, "r")
print(f)

CodePudding user response:

I hope this answers your question. Not sure why your code is so repetitive.

def open_file(path:str) -> None:
    try:
        with open(path, "r") as file:
            #do stuff with file
            for line in file:
                print(line)
    except FileNotFoundError:
        print(f"File was not found in path: {path}.")

if __name__ == "__main__":
    path = "C:\\Users\\dejon\\Desktop\\Python Training\\demo.txt"
    open_file(path)
  • Related