问题
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?
回答1:
If you want to make it multiplatform I would recommend
import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))
回答2:
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+")
回答3:
This is no different than referring to a file via anything else besides Python, you need to use an absolute path rather than a relative one.
If you'd like to refer to files relative to the location of the script, you can also use the __file__ attribute in your module to get the location of the currently running module.
Also, rather than using a shell function, just give your script a shebang line (#!/usr/bin/env python), chmod +x it, and put it someplace on your PATH.
回答4:
You could simply run the function in a subshell so you can cd home before running it:
function testprogram() { (
cd && python .folder/.testprogram.py
) }
回答5:
In python sys.argv[0] will be set to the path of the script (if known). You can use this plus the functions in os.path to access files relative to the directory containing the script. For example
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 sys.argv[0] may not be a full pathname. Instead of using sys.argv[0] you can use __file__ if this is the case.
回答6:
Use either full path like
/path/to/my/folder2/test.txt
or abbreviated one
~/folder2/test.txt
来源:https://stackoverflow.com/questions/12184161/openfile-from-anywhere