如何制作“始终相对于当前模块"文件路径? [英] How to make an "always relative to current module" file path?

查看:19
本文介绍了如何制作“始终相对于当前模块"文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个包含

myfile = open('test.txt', 'r')

test.txt"文件在同一个文件夹中.如果您将运行该模块,该文件将成功打开.

And the 'test.txt' file is in the same folder. If you'll run the module, the file will be opened successfully.

现在,假设您从另一个文件夹中的另一个模块导入该模块.不会在与该代码所在的模块相同的文件夹中搜索该文件.

Now, let's say you import that module from another one which is in another folder. The file won't be searched in the same folder as the module where that code is.

那么如何让模块先在同一个文件夹中搜索具有相对路径的文件呢?

使用__file__"或os.getcwd()"有多种解决方案,但我希望有一种更简洁的方法,比如在您传递给 open() 或 file() 的字符串.

There are various solutions by using "__file__" or "os.getcwd()", but I'm hoping there's a cleaner way, like same special character in the string you pass to open() or file().

推荐答案

解决方案是使用 __file__ 并且很干净:

The solution is to use __file__ and it's pretty clean:

import os

TEST_FILENAME = os.path.join(os.path.dirname(__file__), 'test.txt')

这篇关于如何制作“始终相对于当前模块"文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆