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]
Related
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())
My script is under the directory:
'C:\\Users\\rikesh.kayastha\\project1\\daas\\src'
My script code is :
file_name_csv = "sample.csv"
os.chdir('C:\\Users\\rikesh.kayastha\\project1\\data')
df.to_csv(file_name_csv,index=False,encoding="utf-8")
This code saves the csv file in my desired directory. But this is just for local machine. How to adjust this without mentioning the local path. The base path is just project1 I want to remove the C:\\Users\\rikesh.kayastha\\ part so that this code will work on every machine.
import os
cudir = os.getcwd()
additional_dir = "\\project1\\data"
newdir = os.path.join(cudir, additional_dir)
print(newdir)
You can use sys.argv[0] to get the location of the script on the local machine, which should allow you to locate the data directory aswell
You can get the user's home directory using pathlib with Path.home().
from pathlib import Path
file_name_csv = "sample.csv"
user_home_directory = Path.home()
project_directory = user_home_directory / "project1"
output_filepath = project_directory / file_name_csv
df.to_csv(output_filepath, index=False, encoding="utf-8")
From which directory are you opening your file?
If it is
C:\roboczy\PythonScripts\test\project1\daas\src>python main.py
Then you can use:
filename = "sample.csv"
df.to_csv(f'../../data/{filename}',index=False,encoding="utf-8")
If you are ruinning scripts from project1 folder:
C:\roboczy\PythonScripts\test\project1>python daas\src\myscript.py
Then you can simply use:
filename = "sample.csv"
df.to_csv(f'data/{filename}',index=False,encoding="utf-8")
Use pathlib library.
from pathlib import Path
file_name_csv = "sample.csv"
current_dir = Path(__file__).parent # returns the folder where your python file is
df.to_csv(current_dir.joinpath(file_name_csv), index=False,encoding="utf-8")
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])
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')
Suppose my python code is executed a directory called main and the application needs to access main/2091/data.txt.
how should I use open(location)? what should the parameter location be?
I found that below simple code will work.. does it have any disadvantages?
file = "\2091\sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');
With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.
If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.
So you can fiddle with something like this:
import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
This code works fine:
import os
def read_file(file_name):
file_handle = open(file_name)
print file_handle.read()
file_handle.close()
file_dir = os.path.dirname(os.path.realpath('__file__'))
print file_dir
#For accessing the file in the same folder
file_name = "same.txt"
read_file(file_name)
#For accessing the file in a folder contained in the current folder
file_name = os.path.join(file_dir, 'Folder1.1/same.txt')
read_file(file_name)
#For accessing the file in the parent folder of the current folder
file_name = os.path.join(file_dir, '../same.txt')
read_file(file_name)
#For accessing the file inside a sibling folder.
file_name = os.path.join(file_dir, '../Folder2/same.txt')
file_name = os.path.abspath(os.path.realpath(file_name))
print file_name
read_file(file_name)
I created an account just so I could clarify a discrepancy I think I found in Russ's original response.
For reference, his original answer was:
import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
This is a great answer because it is trying to dynamically creates an absolute system path to the desired file.
Cory Mawhorter noticed that __file__ is a relative path (it is as well on my system) and suggested using os.path.abspath(__file__). os.path.abspath, however, returns the absolute path of your current script (i.e. /path/to/dir/foobar.py)
To use this method (and how I eventually got it working) you have to remove the script name from the end of the path:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
The resulting abs_file_path (in this example) becomes: /path/to/dir/2091/data.txt
It depends on what operating system you're using. If you want a solution that is compatible with both Windows and *nix something like:
from os import path
file_path = path.relpath("2091/data.txt")
with open(file_path) as f:
<do stuff>
should work fine.
The path module is able to format a path for whatever operating system it's running on. Also, python handles relative paths just fine, so long as you have correct permissions.
Edit:
As mentioned by kindall in the comments, python can convert between unix-style and windows-style paths anyway, so even simpler code will work:
with open("2091/data/txt") as f:
<do stuff>
That being said, the path module still has some useful functions.
I spend a lot time to discover why my code could not find my file running Python 3 on the Windows system. So I added . before / and everything worked fine:
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')
Try this:
from pathlib import Path
data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"
f = open(file_to_open)
print(f.read())
Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!
Code:
import os
script_path = os.path.abspath(__file__)
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list)-1]
rel_path = "main/2091/data.txt"
path = "/".join(script_directory) + "/" + rel_path
Explanation:
Import library:
import os
Use __file__ to attain the current script's path:
script_path = os.path.abspath(__file__)
Separates the script path into multiple items:
path_list = script_path.split(os.sep)
Remove the last item in the list (the actual script file):
script_directory = path_list[0:len(path_list)-1]
Add the relative file's path:
rel_path = "main/2091/data.txt
Join the list items, and addition the relative path's file:
path = "/".join(script_directory) + "/" + rel_path
Now you are set to do whatever you want with the file, such as, for example:
file = open(path)
import os
def file_path(relative_path):
dir = os.path.dirname(os.path.abspath(__file__))
split_path = relative_path.split("/")
new_path = os.path.join(dir, *split_path)
return new_path
with open(file_path("2091/data.txt"), "w") as f:
f.write("Powerful you have become.")
If the file is in your parent folder, eg. follower.txt, you can simply use open('../follower.txt', 'r').read()
Get the path of the parent folder, then os.join your relative files to the end.
# get parent folder with `os.path`
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# now use BASE_DIR to get a file relative to the current script
os.path.join(BASE_DIR, "config.yaml")
The same thing with pathlib:
# get parent folder with `pathlib`'s Path
from pathlib import Path
BASE_DIR = Path(__file__).absolute().parent
# now use BASE_DIR to get a file relative to the current script
BASE_DIR / "config.yaml"
Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt (hint: it does), then that will work fine.
You may find that the easiest way to answer a question like this is to try it and see what happens.
Not sure if this work everywhere.
I'm using ipython in ubuntu.
If you want to read file in current folder's sub-directory:
/current-folder/sub-directory/data.csv
your script is in current-folder
simply try this:
import pandas as pd
path = './sub-directory/data.csv'
pd.read_csv(path)
When I was a beginner I found these descriptions a bit intimidating. As at first I would try
For Windows
f= open('C:\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)
and this would raise an syntax error. I used get confused alot. Then after some surfing across google. found why the error occurred. Writing this for beginners
It's because for path to be read in Unicode you simple add a \ when starting file path
f= open('C:\\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)
And now it works just add \ before starting the directory.
In Python 3.4 (PEP 428) the pathlib was introduced, allowing you to work with files in an object oriented fashion:
from pathlib import Path
working_directory = Path(os.getcwd())
path = working_directory / "2091" / "sample.txt"
with path.open('r+') as fp:
# do magic
The with keyword will also ensure that your resources get closed properly, even if you get something goes wrong (like an unhandled Exception, sigint or similar)