Working on OS X Lion, I'm trying to open a file in my python-program from anywhere in the terminal. I have set the following function in my .bash_profile:
function testprogram() {python ~/.folder/.testprogram.py}
This way I can(in the terminal) run my testprogram from a different directory than my ~/.
Now, if I'm in my home directory, and run the program, the following would work
infile = open("folder2/test.txt", "r+")
However, if I'm in a different directory from my home-folder and write "testprogram" in the terminal, the program starts but is unable to find the file test.txt.
Is there any way to always have python open the file from the same location unaffected of where i run the program from?
Use the tilde to represent the home folder, just as you would in the .bash_profile
, and use os.path.expanduser
.
import os
infile = open(os.path.expanduser("~/folder2/test.txt"), "r+")
If you want to make it multiplatform I would recommend
import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With