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?
Asked
Active
Viewed 7,200 times
8
cybertextron
- 10,547
- 28
- 104
- 208
-
4`os.path.expanduser` doesn't work for you? – Joel Cornett Jan 08 '15 at 20:32
-
@JoelCornett I'm guessing the OP didn't know about it, not that it didn't work for them. – SethMMorton Jan 08 '15 at 20:59
1 Answers
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.