Accessing database file from any OS path in Python [duplicate] - python

I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts the desire path in this case is /home/kristina/desire-directory
I know sys.path[0] from sys. But I don't want to parse sys.path[0] resulting string. Is there any another way to get parent of current directory in Python?

Using os.path
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 os.path.abspath(__file__) to obtain the absolute path of the script, and call os.path.dirname twice:
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 os.path.dirname as many times as needed. Example:
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())
Using pathlib
You could also use the pathlib module (available in Python 3.4 or newer).
Each pathlib.Path instance have the parent attribute referring to the parent directory, as well as the parents attribute, which is a list of ancestors of the path. Path.resolve may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute instead if that isn't a desired behaviour.
Path(__file__) and Path() 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 use
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 d is a Path instance, which isn't always handy. You can convert it to str easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'

Use Path.parent from the pathlib module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent to go further in the path:
Path(__file__).parent.parent

This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())

import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')

For me, this is what worked:
from os import path
path.dirname(path.dirname(__file__))
You get the current directory using the current file as a reference, and then call the path.dirname again to get the parent directory.

'..' returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory.

You can simply use../your_script_name.py
For example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csv located in trading system/data/. You simply need to refer to it as ../data/volume.csv

import os def parent_directory(): # Create a relative path to the
parent # of the current working directory
path = os.getcwd()
parent = os.path.dirname(path)
relative_parent = os.path.join(path, parent)
# Return the absolute path of the parent directory
return relative_parent
print(parent_directory())

import os
import sys
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)

from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])

Related

I try to get to the directory of where the current python script is located [duplicate]

How do I get the current file's directory path?
I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
But I want:
'C:\\python27\\'
The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.
Python 3
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()
Python 2 and 3
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 file is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ 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.
References
pathlib in the python documentation.
os.path - Python 2.7, os.path - Python 3
os.getcwd - Python 2.7, os.getcwd - Python 3
what does the __file__ variable mean/do?
Using Path from pathlib is the recommended way since Python 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.
In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__) is the path to the current file.
.parent gives you the directory the file is in.
.absolute() gives you the full absolute path to it.
Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).
Try this:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print(os.path.dirname(__file__))
I found the following commands return the full path of the parent directory of a Python 3 script.
Python 3 Script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 and above script.
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See #RonKalian answer
dir3 = Path(__file__).parent.absolute() #See #Arminius answer
dir4 = Path(__file__).parent
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')
REMARKS !!!!
dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
Given that Path(__file__).is_absolute() is True, the use of the .absolute() method in dir3 appears redundant.
The shortest command that works is dir4.
Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
USEFUL PATH PROPERTIES IN PYTHON:
from pathlib import Path
#Returns the path of the current directory
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))
#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))
#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))
#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))
#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))
OUTPUT:
ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED
Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2
File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv
isfileExist : True
isadirectory : False
File extension : .csv
works also if __file__ is not available (jupyter notebooks)
import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
Also uses pathlib, which is the object oriented way of handling paths in python 3.
IPython has a magic command %pwd to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd can be used directly as following:
present_working_directory = %pwd
I have made a function to use when running python under IIS in CGI in order to get the current folder:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
return path[len(path)-1]
Python 2 and 3
You can simply also do:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
Which outputs something like:
C:\my_folder\sub_folder\
This can be done without a module.
def get_path():
return (__file__.replace(f"<your script name>.py", ""))
print(get_path())

How to remove a file from Path object in Pathlib module?

I have a Path Object representing C:\Users\users\Downloads\img.jpg. How do I get it so the Path only represents C:\Users\user\Downloads? I don't want to delete the file, but rather go back in the Path object itself.
from pathlib import Path
path = Path('C:/Users/user/Downloads/img.jpg')
# Want to get path only to C:\Users\user\Downloads
I would utilize the PurePath class within pathlib as follows:
from pathlib import PurePath
path = PurePath('C:/Users/user/Downloads/img.jpg')
parent = path.parents[0]
This yields: PureWindowsPath('C:/Users/users/Downloads')

How to delete a file by extension in Python?

I was messing around just trying to make a script that deletes items by ".zip" extension.
import sys
import os
from os import listdir
test=os.listdir("/Users/ben/downloads/")
for item in test:
if item.endswith(".zip"):
os.remove(item)
Whenever I run the script I get:
OSError: [Errno 2] No such file or directory: 'cities1000.zip'
cities1000.zip is obviously a file in my downloads folder.
What did I do wrong here? Is the issue that os.remove requires the full path to the file? If this is the issue, than how can I do that in this current script without completely rewriting it.
You can set the path in to a dir_name variable, then use os.path.join for your os.remove.
import os
dir_name = "/Users/ben/downloads/"
test = os.listdir(dir_name)
for item in test:
if item.endswith(".zip"):
os.remove(os.path.join(dir_name, item))
For this operation you need to append the file name on to the file path so the command knows what folder you are looking into.
You can do this correctly and in a portable way in python using the os.path.join command.
For example:
import os
directory = "/Users/ben/downloads/"
test = os.listdir( directory )
for item in test:
if item.endswith(".zip"):
os.remove( os.path.join( directory, item ) )
Alternate approach that avoids join-ing yourself over and over: Use glob module to join once, then let it give you back the paths directly.
import glob
import os
dir = "/Users/ben/downloads/"
for zippath in glob.iglob(os.path.join(dir, '*.zip')):
os.remove(zippath)
I think you could use Pathlib-- a modern way, like the following:
import pathlib
dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.glob(dir / "*.zip")
for zf in zip_files:
zf.unlink()
If you want to delete all zip files recursively, just write so:
import pathlib
dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.rglob(dir / "*.zip") # recursively
for zf in zip_files:
zf.unlink()
Just leaving my two cents on this issue: if you want to be chic you can use glob or iglob from the glob package, like so:
import glob
import os
files_in_dir = glob.glob('/Users/ben/downloads/*.zip')
# or if you want to be fancy, you can use iglob, which returns an iterator:
files_in_dir = glob.iglob('/Users/ben/downloads/*.zip')
for _file in files_in_dir:
print(_file) # just to be sure, you know how it is...
os.remove(_file)
origfolder = "/Users/ben/downloads/"
test = os.listdir(origfolder)
for item in test:
if item.endswith(".zip"):
os.remove(os.path.join(origfolder, item))
The dirname is not included in the os.listdir output. You have to attach it to reference the file from the list returned by said function.
Prepend the directory to the filename
os.remove("/Users/ben/downloads/" + item)
EDIT: or change the current working directory using os.chdir.

python code to get the files outside the current working directory

using python code how can i get the files outside the current working directory
am working with e:\names\test.py directory
dirpath = os.path.dirname(os.path.realpath(__file__))
dirpath prints e:\names
in e:\images
how can i get the path e:\images\imh.png from the file test.py
Am hardcode the above path in test.py,how can i set the relative path inside test.py file
You can use:
os.path.split(os.getcwd())[0] to get the parent directory.
Then, you can use:
a=os.path.split(os.getcwd())[0]
os.listdir(a)
for listing the contents of the parent directory
Also, this works too:-
os.listdir(os.pardir)
import sys
import os
sys.path.insert(1, os.path.split(os.getcwd())[0] + '/directory_name')

os.path.dirname(__file__) returns empty

I want to get the path of the current directory under which a .py file is executed.
For example a simple file D:\test.py with code:
import os
print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)
It is weird that the output is:
D:\
test.py
D:\test.py
EMPTY
I am expecting the same results from the getcwd() and path.dirname().
Given os.path.abspath = os.path.dirname + os.path.basename, why
os.path.dirname(__file__)
returns empty?
Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have
os.path.dirname(filename) + os.path.basename(filename) == filename
Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.
To get the dirname of the absolute path, use
os.path.dirname(os.path.abspath(__file__))
import os.path
dirname = os.path.dirname(__file__) or '.'
os.path.split(os.path.realpath(__file__))[0]
os.path.realpath(__file__)return the abspath of the current script; os.path.split(abspath)[0] return the current dir
can be used also like that:
dirname(dirname(abspath(__file__)))
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
Since Python 3.4, you can use pathlib to get the current directory:
from pathlib import Path
# get parent directory
curr_dir = Path(__file__).parent
file_path = curr_dir.joinpath('otherfile.txt')
None of the above answers is correct. OP wants to get the path of the current directory under which a .py file is executed, not stored.
Thus, if the path of this file is /opt/script.py...
#! /usr/bin/env python3
from pathlib import Path
# -- file's directory -- where the file is stored
fd = Path(__file__).parent
# -- current directory -- where the file is executed
# (i.e. the directory of the process)
cwd = Path.cwd()
print(f'{fd=} {cwd=}')
Only if we run this script from /opt, fd and cwd will be the same.
$ cd /
$ /opt/script.py
cwd=PosixPath('/') fd=PosixPath('/opt')
$ cd opt
$ ./script.py
cwd=PosixPath('/opt') fd=PosixPath('/opt')
$ cd child
$ ../script.py
cwd=PosixPath('/opt/child') fd=PosixPath('/opt/child/..')
I guess this is a straight forward code without the os module..
__file__.split(__file__.split("/")[-1])[0]

Categories