Open (file) from anywhere

While working with OS X Lion, I am trying to open a file in my python program from anywhere in the terminal. I installed the following function in my .bash_profile:

function testprogram() {python ~/.folder/.testprogram.py}

Thus, I can (in the terminal) run my test program from a different directory than my ~ /.

Now, if I run the program in my home directory, the following will work

infile = open("folder2/test.txt", "r+")

However, if I enter another directory from my home folder and write "testprogram" in the terminal, the program starts, but cannot find the test.txt file.

Is there a way to always have python to open the file from the same place where I did not run the program?

+5
source share
6 answers

If you want to make it multi-platform, I would recommend

import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))
+8

, .bash_profile, os.path.expanduser.

import os
infile = open(os.path.expanduser("~/folder2/test.txt"), "r+")
+8

, - , Python, , .

script, __file__ , .

, script shebang (#!/usr/bin/env python), chmod +x PATH.

0

, cd , :

function testprogram() { (
    cd && python .folder/.testprogram.py
) }
0

In python sys.argv[0], the script path will be set (if known). You can use this plus function in os.pathto access files relative to the directory containing the script. for instance

import sys, os.path

script_path = sys.argv[0]
script_dir = os.path.dirname(script_path)

def script_relative(filename):
  return os.path.join(script_dir, filename)

infile = open(script_relative("folder2/test.txt"), "r+")

David Robinson points out that it sys.argv[0]may not be the full path name. Instead of using, sys.argv[0]you can use __file__if it is.

0
source

Use full path e.g.

/path/to/my/folder2/test.txt

or abbreviated

~/folder2/test.txt 
-1
source

All Articles