0

I can't find out how to find a relative path in 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?

  • Where are you calling this script from? Python's relative paths are based on where the executable is invoked. What command are you running to run the script? – C.Nivs Mar 17 '20 at 18:46
  • 1
    What *output* is generated from your first script? Passing an invalid path to your ConfigParser object will return an empty object. So if `main.ini` is not found, then the call to `config['data']` should raise a KeyError. – wstk Mar 17 '20 at 18:53
  • @wstk you're right, it does raise a KeyError. Is there a script that can help me find the relative path? Thanks!!! – Alex Liu 33214 Mar 17 '20 at 22:17
  • 1
    As @C.Nivs mentioned the path is resolved *relative to the path where the executable is invoked*. So in your example wherever you run the script from, it expects there to be a file (`main.ini`) in the parent directory. I will add an answer for how you can resolve the path relative to the *location of the script*. – wstk Mar 18 '20 at 10:52

2 Answers2

1

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.

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)

In your case, assuming that your main.ini is in the parent directory of the script you are running,you could do

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. 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.

wstk
  • 1,040
  • 8
  • 14
0

I think it is just the onedrive. It is forcing you to use a strait forward path