简体   繁体   English

如何通过传递包含文件所在目录的变量名来打开文件 python?

[英]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.

相关问题 如何避免python在代码所在目录运行文件? - How to avoid python running file in the directory where the code is located? 使用 python 获取目录中包含最新时间戳的文件名 - Get the file name which contains the latest timestamp in a directory using python Python传递用户输入的文件名来打开 - Python passing user input of name of file to open 打开一个名称包含在变量中的文件 - open a file which name is contained in a variable 使用“打开”时文件位于何处? - Where is file located when using "with open"? 如何在python中打开文件名并附加日期的文件? - How to open a file in python which has it's name appended with date? 为什么 python 程序在我将文件移动到另一个目录后继续写入它原来所在的目录? - Why does a python program continue to write to the directory in which it was originally located, after I move the file to another directory? 如何打开与 Python 脚本位于同一文件夹中的文件 - How to open file located in same folder as Python script tesseract可执行文件在MacOS上的哪里,以及如何在Python中定义它? - Where is the tesseract executable file located on MacOS, and how to define it in Python? 使用包含文件名 Python 的变量打开文件 - Opening File Using a Variable that Contains File Name Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM