0

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?

Ivan
  • 63,011
  • 101
  • 250
  • 382

1 Answers1

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