简体   繁体   中英

how to open a file by passing a variable name which contains the directory where the file is located in python?

I'm working on a function where I need to open a file eg "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)

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)

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