473,408 Members | 2,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Find directory name of file?

I'm pretty new at Python, so I have no idea how to do this: How do I
find the name of the directory that contains the application currently
being executed (e.g. if the file is /home/user/file.py, I want to get
the /home/user part)?

Thanks!

Jan 29 '06 #1
9 2536

veracon wrote:
I'm pretty new at Python, so I have no idea how to do this: How do I
find the name of the directory that contains the application currently
being executed (e.g. if the file is /home/user/file.py, I want to get
the /home/user part)?

Thanks!


look into os.path module for help

Jan 29 '06 #2
also the function os.cwd()
;-)

Jan 29 '06 #3
jm*********@gmail.com wrote:
also the function os.cwd()
;-)


I'm not sure how os.cwd() helps, but generally the solution to this
starts with pointing out that sys.argv[0] usually contains the path to
the main script, which is often the answer needed.

Recipes have been posted in the past which cover a wider range of
situations, including when running as a "py2exe'd" program (i.e.
"frozen"), as the simple solution doesn't cover all cases.

Checking the archives would probably help.

-Peter

Jan 29 '06 #4
On 2006-01-29, jm*********@gmail.com <jm*********@gmail.com> wrote:
also the function os.cwd()


Neither os.path nor os.cwd are going to tell you the location
of the python program being executed.

Looking at the value of sys.argv[0] is probably the best bet.
If it's a relative path, then you can use os.path to convert it
to an absolute path if you like:

Try something like this at the beginning of your program and
see if it does what you want:

print os.path.abspath(sys.argv[0])

--
Grant Edwards grante Yow! It's the land of
at DONNY AND MARIE as promised
visi.com in TV GUIDE!
Jan 29 '06 #5
ngw
-veracon <ve*****@gmail.com>:
I'm pretty new at Python, so I have no idea how to do this: How do I
find the name of the directory that contains the application currently
being executed (e.g. if the file is /home/user/file.py, I want to get
the /home/user part)?


Try os.path.dirname (__file__)

HTH,
ngw
Jan 30 '06 #6

Peter Hansen wrote:
jm*********@gmail.com wrote:
also the function os.cwd()
;-)
I'm not sure how os.cwd() helps, but generally the solution to this
starts with pointing out that sys.argv[0] usually contains the path to
the main script, which is often the answer needed.

Recipes have been posted in the past which cover a wider range of
situations, including when running as a "py2exe'd" program (i.e.
"frozen"), as the simple solution doesn't cover all cases.

Checking the archives would probably help.


There are a couple of functions from `pathutils
<http://www.voidspace.org.uk/python/pathutils.html>`_ that do this
(originally supplied by Thomas Heller I believe) :

def main_is_frozen():
"""Return ``True`` if we're running from a frozen program."""
import imp
return (
# new py2exe
hasattr(sys, "frozen") or
# tools/freeze
imp.is_frozen("__main__"))

def get_main_dir():
"""Return the script directory - whether we're frozen or not."""
if main_is_frozen():
return os.path.abspath(os.path.dirname(sys.executable))
return os.path.abspath(os.path.dirname(sys.argv[0]))

just call ``get_main_dir()`` and it works consistently with py2exe'd
scripts and normal scripts.

All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
-Peter


Jan 30 '06 #7

ngw wrote:

Try os.path.dirname (__file__)


what O/S and python release are you using? I get NameError: '__file__'
not defined in win32 and OS X (both are 2.4.x, installed from
ActiveState installers)

Jan 30 '06 #8

Grant Edwards wrote:
Try something like this at the beginning of your program and
see if it does what you want:

print os.path.abspath(sys.argv[0])


Wanna see something freaky?

In IDLE, I type the following:
import sys
import os.path
os.path.abspath(sys.argv[0]) 'C:\\Program Files\\Python\\2.4'
Pretty normal, right? Then I type this:
print sys.argv[0]
Yup. No output. Even if I wrap the sys.argv[0] in something visible,
there's nothing there:
print "x"+str(sys.argv[0])+"y" xy


How does it know what the path of the argument is if it doesn't know
what the argument is? Seems a bit presumptive to assume that CWD is
the path to a blank string...unless abspath presumes that anything you
pass it is an executable, even if it's got no bytes...

--Blair

Jan 30 '06 #9
Blair P. Houghton wrote:
Wanna see something freaky?

In IDLE, I type the following:
>>> import sys
>>> import os.path
>>> os.path.abspath(sys.argv[0]) 'C:\\Program Files\\Python\\2.4'

Pretty normal, right?
Depends on your definition of normal. That doesn't look to me like it's
the path to IDLE. Anyway, sys.argv[0] is probably documented as being
undefined when you run an interactive session...
Then I type this:
>>> print sys.argv[0] >>>

Yup. No output. Even if I wrap the sys.argv[0] in something visible,


The correct way to see what's really in a string is to call repr() on
it, as in "print repr(sys.argv[0])". That would show you that it's
merely the empty string ''.
How does it know what the path of the argument is if it doesn't know
what the argument is? Seems a bit presumptive to assume that CWD is
the path to a blank string...unless abspath presumes that anything you
pass it is an executable, even if it's got no bytes...


os.path.abspath('') is merely returning the current directory. It does
seem sort of implicit, but it's doubtless behaviour that is counted on
by many applications at this point, so I'm afraid it's unlikely to
change, even if it wasn't such a good idea. (And it might well be an
excellent idea...)

-Peter

Jan 30 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Xah Lee | last post by:
suppose you want to do find & replace of string of all files in a directory. here's the code: ©# -*- coding: utf-8 -*- ©# Python © ©import os,sys © ©mydir= '/Users/t/web'
1
by: Dan Jones | last post by:
I'm writing a script to process a directory tree of images.  In each directory, I need to process each image and generate an HTML file listing all of the images and links to the subdirectories....
2
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified...
2
by: graphicsxp | last post by:
Hi, How can I open all the files in a directory, which names match a particular string ? Say I have a string like 'a file name to find' and I want to find and open all the files of a given...
6
by: Mudcat | last post by:
Hi, I can't figure out why ctypes won't load the DLL I need to use. I've tried everything I can find (and the ctypes website is down at the moment). Here's what I've seen so far. I've added...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.