The special variable contains the path to the current file. From that we can get the directory using either __file__ or the pathlib module.os.path
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after is two underscores, not just one.file
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.__file__
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used to change your current working directory, since the value of the os.chdir() constant is relative to the current working directory and is not changed by an __file__ call.)os.chdir()
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
os and os.path modules.__file__ constantos.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path) (returns "the directory name of pathname path")os.getcwd() (returns "a string representing the current working directory")os.chdir(path) ("change the current working directory to path")It looks like there is a element that contains all the parent directories of a given path. E.g., if you start with:parents
>>> import pathlib
>>> p = pathlib.Path('/path/to/my/file')
Then is the directory containing p.parents[0]:file
>>> p.parents[0]
PosixPath('/path/to/my')
...and will be the next directory up:p.parents[1]
>>> p.parents[1]
PosixPath('/path/to')
Etc.
is another way to ask for p.parent. You can convert a p.parents[0] into a string and get pretty much what you would expect:Path
>>> str(p.parent)
'/path/to/my'
And also on any you can use the Path method to get an absolute path:.absolute()
>>> os.chdir('/etc')
>>> p = pathlib.Path('../relative/path')
>>> str(p.parent)
'../relative'
>>> str(p.parent.absolute())
'/etc/../relative'
Note that and os.path.dirname treat paths with a trailing slash differently. The pathlib parent of pathlib is some/path/:some
>>> p = pathlib.Path('some/path/')
>>> p.parent
PosixPath('some')
While on os.path.dirname returns some/path/:some/path
>>> os.path.dirname('some/path/')
'some/path'
It seems that this method was brought up in a bug report here. Some code was written (given here) but unfortunately it doesn't seem that it made it into the final Python 3.4 release.
Incidentally the code that was proposed was extremely similar to the code you have in your question:
# As a method of a Path object
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return self.__class__(os.path.expanduser(str(self)))
Here is a rudimentary subclassed version which subclasses PathTest (I'm on a Windows box but you could replace it with WindowsPath). It adds a PosixPath based on the code that was submitted in the bug report.classmethod
from pathlib import WindowsPath
import os.path
class PathTest(WindowsPath):
def __new__(cls, *args, **kwargs):
return super(PathTest, cls).__new__(cls, *args, **kwargs)
@classmethod
def expanduser(cls):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return cls(os.path.expanduser('~'))
p = PathTest('C:/')
print(p) # 'C:/'
q = PathTest.expanduser()
print(q) # C:\Users\Username
I'm not quite sure I understand what you're trying to do.
However, it's no wonder you're getting stuck in a loop: by re-initializing you're starting all over again every time!p.glob()
is actually a generator object, which means it will keep track of its progress by itself. You may just use it the way it was meant to be used: by just iterating over it.p.glob()
So, for instance, you might be better served by the following:
redpath = os.path.realpath('.')
thispath = os.path.realpath(redpath)
thispath = os.path.realpath(thispath+'/../../../..')
p = Path(thispath)
chosen = None
for text_file in p.glob('**/*.fits'):
print("Is this the correct file path?")
print(text_file)
userinput = input("y or n")
if userinput == 'y':
chosen = text_file
break
if chosen:
print ("You chose: " + str(chosen))
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use .__file__
Inside the script use to obtain the absolute path of the script, and call os.path.abspath(__file__) twice:os.path.dirname
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling as many times as needed. Example:os.path.dirname
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use :os.getcwd
import os
d = os.path.dirname(os.getcwd())
You could also use the module (available in Python 3.4 or newer).pathlib
Each instance have the pathlib.Path attribute referring to the parent directory, as well as the parent attribute, which is a list of ancestors of the path. parents may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.resolve instead if that isn't a desired behaviour.Path.absolute
and Path(__file__) represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would usePath()
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that is a d instance, which isn't always handy. You can convert it to Path easily when you need it:str
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'