Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open(file) from anywhere

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?

like image 628
Noorac Avatar asked Aug 29 '12 18:08

Noorac


2 Answers

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+")
like image 97
David Robinson Avatar answered Oct 18 '22 21:10

David Robinson


If you want to make it multiplatform I would recommend

import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))
like image 42
Joran Beasley Avatar answered Oct 18 '22 21:10

Joran Beasley