why this function return False although the image already exists in that path and I wrote its name correctly
import cv2
import os
print(os.path.isfile('../Project/mark-zuker.png'))
The program is probably run from another directory. If you have those statements in a script, try with the absolute path:
code_dir = os.path.dirname(os.path.realpath(__file__))
file_img = os.path.dirname(code_dir) + '/Project/mark-zuker.png'
print(file_img)
print(os.path.isfile(file_img))
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())
I have a custom PyPi package. It is installed under Pyhon\Python38\Lib\site-packages\myCustomPackage.
In the __init__ code for myCustomPackage, I perform a few different directory operations, which failed to find the correct files and directories which reside in the Pyhon\Python38\Lib\site-packages\myCustomPackage folder.
I looked at the output of os.getcwd() and it showed the cwd to be C:\Users\TestUser, which is the root Windows user folder.
I would like the root folder to be the myCustomPackage folder.
For example, the file \myCustomPackage\__init__.py would contain
import os
class myCustomPackage():
def __init__(self):
print(os.getcwd())
If I run:
from myCustomPackage import myCustomPackage
theInstance = myCustomPackage()
The output is:
C:\Users\TestUser
How can I change that to be C:\Users\TestUser\AppData\Local\Programs\Python\Python38\Lib\site-packages\myCustomPackage?
Note : I would want it to be dynamic. No hard coding, in case the python version changes or the Windows user changes.
To get the directory path of the current module, you can use the built-in __file__.
To set the cwd to the module directory, use:
import os
import sys
from pathlib import Path
class myCustomPackage():
def __init__(self):
module_directory = Path(__file__).parent
os.chdir(module_directory)
print(os.getcwd())
My solution was the following function:
import site
import os
import traceback
def changeCWD(self):
try:
sitePackages = site.getsitepackages()
site_packages_dir = sitePackages[1]
top_module_dir = site_packages_dir + os.path.sep + "myCustomPackage"
os.chdir(top_module_dir)
return True
except:
self.myLogger.error("An error occurred in changeCWD")
tb = traceback.format_exc()
self.myLogger.exception(tb)
return False
Error image
from pathlib import Path
import linecache
import pyperclip
print('Looking for a path...')
print('Found path!')
Path('C:/Users/Akush/Documents/Warcraft III/CustomMapData/YouTD/')
a = linecache.getline('savecode.txt',7)
pyperclip.copy(a)
print('{} copied to clipboard!'.format(a))
So everything works fine in pycharm, but when i made .exe from .py it gives "Module not found" error in CMD
Do you know what i did wrong here?
thanks for help!
Since you are using pycharm, make sure you are using the correct python interpreter in the project settings. If you are using the system interpreter, the modules won't be found in a virtual environment
I cleaned up your code a little:
import os
from pathlib import Path
import linecache
import pyperclip
# Specify the path
dir = Path('C:/Users/Akush/Documents/Warcraft III/CustomMapData/YouTD/')
# Specify the file
file = 'savecode.txt'
# Start Searching for Path
print('Looking for a path...')
# Check if Path exists
if dir.is_dir():
# Set the currect working directory to the found path
os.chdir(dir)
# Let the user know the path has been found
print('Found path!')
# Check to see if the file exists
if Path(file).is_file():
# Get lines from file
a = linecache.getline(file, 7)
if a == '':
print('Nothing found in file')
else:
# Copy line to clipboard
pyperclip.copy(a)
print(f'{a} copied to clipboard!')
else:
print("File not found")
else:
print('This directory does not exist')
I have the following code:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{destination}/data.pdf')
I want the pdf to be saved in windows equivalent of /home/[username]/datafolder. I don't really need to use use linux or mac but for academic reasons i have decided to use the relative path method.
This code makes sense to me but for some reason it is not the directory i want it to be because when i specify the path this way the pdf generator, generates an error.
Error: Unable to write to destination
Exit with code 1, due to unknown error.
I know the error is in the last line of code where i have specified '/relative_path/data.pdf'. Could you please advise how i can resolve this issue?
Update 1:
As suggested by #Matthias I have updated the code but I am still getting the same error
Update 2:
I tried:
from pathlib import Path
destination = Path.home()
try:
os.mkdir(destination\Data)
except OSError as error:
print(error)
But it is still not pointing to the directory Data
Update 3
I know i am getting closer:
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
At this point the code is executes but the folder Data was not created not am i able to locate data.pdf. I did get sucessful run though:
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Any ideas on how i can get this working correctly? The code does not produce the folder or the file?
Just check by putting
relative_path line before os.makedirs
As below
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
#path = os.path.join("home","{username}","Data")
# in case of window you will need to add drive "c:" or "d:" before os.path.sep
path = os.path.join(,"home",username,"Data")
relative_path = os.path.relpath(path, os.getcwd())
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
Maybe you could change your last line to:
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
in order to get it to save to the home directory.
Perhaps the issue is that the directory doesn't exist. You could use os.makedirs to create the directory, using the exist_ok=True flag in case the directory already exists. Like so:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(path, exist_ok=True)
pdfkit.from_url('www.google.com', f'{path}/data.pdf')
You can use os.environ. Run this little script on your machine:
import os
for key, value in os.environ.items():
print(key, '-->', value)
and see for yourself what you need exactly. It's portable as well.
Let's say you want to get the path of the user's home directory. You could get it from os.environ['HOME'] and then create the path to the target directory using os.path.join(os.environ['HOME'], 'target_directory_name').
You won't be able to create files in a directory if you don't have the required permissions, though.
User folders in windows are stored in "/Users/{username}/*". I don't know if you are trying to make this compatible for multiple OSs but if you just want to make this run on windows try:
path = f"/Users/{username}/Data"
start = f"/Users/{username}"
Hope it works.:)
Edit:
To get the home directory of a user regardless of OS you could use
from pathlib import Path
home = str(Path.home())
sorry for the late edit.
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')