简体   繁体   English

Python 如何管理相对路径

[英]How Python manages relative path

I can't find out how to find a relative path in Python.我不知道如何在 Python 中找到相对路径。 The code only allows me to use the absolute path.代码只允许我使用绝对路径。

What I want我想要的是

config = configparser.ConfigParser()
config.read('..\\main.ini',)
print(config.sections())
FilePaths = config['data']
DictionaryFilePath = FilePaths['DictionaryFilePath']
print(DictionaryFilePath)

what it forces me to do它迫使我做什么

config = configparser.ConfigParser()
config.read('C:\\Users\\***confendential***\\OneDrive\\文档\\Python\\Chinese for practice\\ChineseWords\\app\\main.ini',)
print(config.sections())

FilePaths = config['data']
DictionaryFilePath = FilePaths['DictionaryFilePath']
print(DictionaryFilePath)

Any Ideas???有任何想法吗???

Is it Onedrive?是 Onedrive 吗?

There are already some answers that cover this here, for example . 例如,这里已经有一些答案涵盖了这一点

To summarise, if you just do总而言之,如果你只是这样做

config.read('..\\main.ini',)

then your program expects a file, main.ini to be located in the parent directory of wherever you executed the program from.那么您的程序需要一个文件main.ini位于您执行程序的任何位置的父目录中。

What you usually want is to specify a path relative to the location of the file that is executing.您通常想要的是指定一个相对于正在执行的文件位置的路径。

You can get the path to that file with __file__ and then manipulate it with the os.path module (see this answer )您可以使用__file__获取该文件的路径,然后使用os.path模块对其进行操作(请参阅此答案

In your case, assuming that your main.ini is in the parent directory of the script you are running,you could do在您的情况下,假设您的main.ini位于您正在运行的脚本的父目录中,您可以这样做

inifile = os.path.join(os.path.dirname(os.path.dirname(__file__)), "main.ini")
config.read(inifile)

Another thing to note in your case, is it could be useful to actually check that the ini file is loaded.在您的情况下要注意的另一件事是,实际检查 ini 文件是否已加载可能很有用。 If the file is not found it just returns an empty object, so you can check this and print a message or error.如果找不到该文件,它只会返回一个空对象,因此您可以检查它并打印一条消息或错误。

Hope this is helpful.希望这是有帮助的。 The other linked answers give some more useful info on these ideas.其他链接的答案提供了一些关于这些想法的更有用的信息。

I think it is just the onedrive.我认为这只是onedrive。 It is forcing you to use a strait forward path它迫使你使用一条狭窄的前进道路

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM