簡體   English   中英

如何通過傳遞包含文件所在目錄的變量名來打開文件 python?

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

我正在處理 function,我需要通過傳遞包含文件所在目錄而不是文件名的變量名來打開文件,例如“hello.txt”。 下面是我為此設計的虛擬代碼。 簡而言之,我需要能夠通過傳遞目錄名稱來打開位於該目錄中的文件,如您在更新中看到的那樣。

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)

我希望這回答了你的問題。 不確定為什么您的代碼如此重復。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM