8

I have the following file: ~/.config.txt which is located in /root/.config. In order to avoid hardcoded paths in my Python file, how can I always replace (and correctly refer) to a ~/ path as <home> in Python? This way I could replace ~/.config.txt by /root/.config if /root/ was my home directory?

cybertextron
  • 10,547
  • 28
  • 104
  • 208

1 Answers1

23

You can use os.path.expanduser to convert ~ into your home directory:

>>> import os
>>> os.path.expanduser('~/.config.txt')
'/root/.config.txt'
>>>

This works on both *nix and Windows systems.