[英]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.我正在处理 function,我需要通过传递包含文件所在目录而不是文件名的变量名来打开文件,例如“hello.txt”。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.