查找与python脚本相同目录下的文件(txt文件)

时间:2021-03-09 06:21:43

标签: python

file = open(r"C:\Users\MyUsername\Desktop\PythonCode\configure.txt")

现在这就是我正在使用的。但是,如果人们在他们的计算机上下载该程序,则该文件将无法链接,因为它是特定路径。如果文件与脚本位于同一文件夹中,我将如何链接该文件。

3 个答案:

答案 0 :(得分:1)

您可以使用 __file__。从技术上讲,并非每个模块都具有此属性,但如果您不是从文件加载模块,那么从同一文件夹加载文本文件无论如何都会成为一个有争议的问题。

from os.path import abspath, dirname, join

with open(join(dirname(abspath(__file__)), 'configure.txt')):
    ...

虽然这可以满足您的要求,但它不一定是存储配置的最佳方式。

答案 1 :(得分:0)

使用 os 模块获取您当前的文件路径。

import os
this_dir, this_filename = os.path.split(__file__)
myfile = os.path.join(this_dir, 'configure.txt') 
file = open(myfile)

答案 2 :(得分:-1)

# import the OS library
import os
# create the absolute location with correct OS path separator to file
config_file = os.getcwd() + os.path.sep + "configure.txt"
# Open file 
file = open(config_file)

此方法将确保使用正确的路径分隔符。