I seek to automate some tasks with Python (version 3.5, but I am also curious about 2.7) instead of shell scripts. And I would be glad if I could write "~/myfile.txt"
instead of /home/me/myfile.txt
. Is this possible?
Asked
Active
Viewed 58 times
0

Ivan
- 63,011
- 101
- 250
- 382
-
2`os.path.expanduser(path)` – ziddarth Dec 23 '15 at 21:39
-
http://stackoverflow.com/questions/10170407/find-home-directory-in-python – Habib Kazemi Dec 23 '15 at 21:40
-
1@l'L'l ok I deleted that comment/flag – Anton Protopopov Dec 23 '15 at 21:50
1 Answers
7
Use os.path.expanduser("~")
for line in open(os.path.expanduser("~/my_file")):
print line
Docs:
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.
https://docs.python.org/2/library/os.path.html#os.path.expanduser

Martin Konecny
- 57,827
- 19
- 139
- 159