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')
Related
I am using shutil to copy my files to another destination directory , what i want to achieve is
src/red.png
src/blue.png
src/green.png
for example if i select blue and green then while saving i want them to be saved as
dst/blue_1001.png
dst/green_1002.png
Thanks
Kartikey
All you need to do is to construct a destination path in a format that you want and shutil will do rest of the job.
I am using pathlib module here because it provides convenient APIs to work with paths.
>>> import shutil
>>> from pathlib import Path
>>>
>>> files_to_copy = ["src/red.png", "src/blue.png"]
>>>
>>> destination = Path("dst")
>>>
>>> for index, file in enumerate(map(Path, files_to_copy), start=1001):
... destination_filename = f"{file.stem}_{index}{file.suffix}"
... print(f"{destination_filename=}")
... _ = shutil.copy(file, destination / destination_filename)
...
destination_filename='red_1001.png'
destination_filename='blue_1002.png'
Shutils supports setting the name of the target file. It mainly depends on how you splice the name of the target file
import shutil
from pathlib import Path
parent_path = Path(__file__).parent
file_path = parent_path.joinpath("test2.py")
shutil.copy(file_path, parent_path.joinpath("test3.py"))
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())
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])
I need to change a prefix for a current file.
An example would look as follows:
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
# Current file with destination
print(file)
# Prefix to be used
file_prexif = 'A'
# Hardcoding wanted results.
Path('/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py')
As can be seen hardcoding it is easy. However is there a way to automate this step?
There is a pseudo - idea of what I want to do:
str(file).split('/')[-1] = str(file_prexif) + str('_') + str(file).split('/')[-1]
I only want to change last element of PosixPath file. However it is not possible to change only last element of string
file.stem accesses the base name of the file without extension.
file.with_stem() (added in Python 3.9) returns an updated Path with a new stem:
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
print(file.with_stem(f'A_{file.stem}'))
\Users\my_name\PYTHON\Playing_Around\A_testing_lm.py
Use file.parent to get the parent of the path and file.name to get the final path component, excluding the drive and root.
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
file_prexif_lst = ['A','B','C']
for prefix in file_prexif_lst:
p = file.parent.joinpath(f'{prefix}_{file.name}')
print(p)
/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/B_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/C_testing_lm.py
I am working on a program that will edit all local files ending in a csv extension. When I call the location of the directory and then change directory I get an error. The error is due to extra \'s being added to the path. How can I call the path without these extra \'s?
I've looked around and there are similar issues but every example I see is for a hard written location and not a movable one.
import os
import glob
import sys
path = os.path.abspath(__file__)
extension = '.csv'
os.chdir(os.path.abspath(__file__))
result = glob.glob('*'.format(extension))
print(path)
print(result)
os.chdir() needs a directory not a file which is what you are giving it. try changing os.chdir(os.path.abspath(__file__)) to os.chdir(os.path.dirname(path))
import os
import glob
import sys
__file__ = 'test.txt'
path = os.path.abspath(__file__)
print(path)
extension = '.csv'
os.chdir(os.path.dirname(path))
result = glob.glob('*'.format(extension))
print(path)
print(result)