[英]read files from directory that has running script rather than calling directory location from where the script was called, python
suppose I have following 假设我有以下
test/
Main.py
test/one/
One.py
test1.txt
test/two/
Two.py
test2.txt
What I want to do is, run Main.py and call One.py and Two.py and want to read files. 我想做的是,运行Main.py并分别调用One.py和Two.py并想要读取文件。 Since directory containing One.py has one file test1.txt, I want to read that file and directory containing Two.py has one file test2.txt
由于包含One.py的目录只有一个文件test1.txt,我想读取该文件,而包含Two.py的目录只有一个文件test2.txt。
This can be done simply by 这可以简单地通过
open("one/test1.txt", "r")
and open("two/test2.txt", "r") in two files 并在两个文件中打开(“ two / test2.txt”,“ r”)
Is there any other way to read files. 还有其他读取文件的方法。 This is simple case I took.
这是我采取的简单情况。
I am facing this problem. 我正面临这个问题。 For this, I have created setting object and provide required location to that directory manually and passed this setting object to all class that needs location to read file
为此,我创建了设置对象,并手动向该目录提供了所需的位置,并将此设置对象传递给需要位置以读取文件的所有类。
Is there different approach? 有不同的方法吗?
If I understand your question correctly, you want to know the directory of the running python file? 如果我正确理解了您的问题,是否想知道正在运行的python文件的目录?
You can access the special variable __file__
inside a Python program. 您可以在Python程序中访问特殊变量
__file__
。 It returns the path of the python file. 它返回python文件的路径。
To open a named file in the running script's directory, use: 要在运行脚本的目录中打开一个命名文件,请使用:
import os
f = open(os.path.join(os.path.dirname(__file__), "filename.txt"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.