Use shell:Programs in python - python

In windows you can use windows + r and type shell:Programs. Im trying to use this in my python script.
I have tryed doing this.
import os
path = os.getenv('shell:Programs')
and
from os import path
path = os.path.expandvars('shell:Programs')
This sadly only works for tags like %appdata%
Help!

Try this:
import os
os.startfile('shell:Programs')
OR
import subprocess
subprocess.call("explorer")
#with file path
#subprocess.call("explorer C:\\")

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())

Relative path not pointing to desired directory

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.

How to remove PythonCode from the path returned by os.path.dirname(__file__)?

I have a python script in PythonCode folder. I want that I should get the path excluding the PythonCode from it when using os.path.dirname(__file__), currently when I am using os.path.dirname(__file__) it is returning this:-
C:\Users\xyz\Documents\ABC\Python Code
but I need this path:-
C:\Users\xyz\Documents\ABC\
import os
dirname = os.path.dirname(__file__)
print (dirname)
You can wrap dirname once again to go up a directory
dirname=os.path.dirname(os.path.dirname(path))
Just call os.path.dirname() again on what you have:
import os
dirname = r"C:\Users\xyz\Documents\ABC\Python Code"
wanted = os.path.dirname(dirname)
print(wanted) # -> C:\Users\xyz\Documents\ABC
This has been already answered here.
You can do something like this,
import os
print(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
The other answers use os.path, but you could also use the standard library pathlib module (https://docs.python.org/3/library/pathlib.html), which some people prefer because of its more intuitive object-oriented interface:
from pathlib import Path
wanted = Path(__file__).parent.parent
wanted_as_string = str(wanted)

'No such file or directory' with absolute Path

I want to import a .png file with
import matplotlib.pyplot as plt
O = plt.imread('C:/Users/myusername/Downloads/Mathe/Picture.png')
I have the absolute Path, but it still gives me the Error:
[Errno 2] No such file or directory
Any suggestions for a python newbie?
At first I used relative Path, switched to absolute Path.
As stated by the previous answer, you shouldn't hard-code paths and in general, to access the home directory of the current user, you can use
os.path.expanduser("~")
and with some input control, your program becomes:
import os
import matplotlib.pyplot as plt
picture_path = os.path.join(os.path.expanduser("~"), "Downloads", "Mathe",
"Picture.png")
if os.path.isfile(picture_path):
im = plt.imread(picture_path)
You can check the full documentation of os.path here.
As Eryk Sun noted in the comments, while in this case it works, In Windows, it's actually not advised to use os.path.expanduser("~") (i.e. the user's profile directory in most cases) because most of the special paths (i.e. known folders) are relocatable in the shell. Use the API to query the Windows shell for the path of a known folder (e.g. FOLDERID_Downloads). There is an example to do so using PyWin32 and if it's not possible to use Pywin32, the answer links to another method using ctypes.
Finally, you may have something like that
import matplotlib.pyplot as plt
import os
import pythoncom
from win32com.shell import shell
kf_mgr = None
def get_known_folder(folder_id):
global kf_mgr
if kf_mgr is None:
kf_mgr = pythoncom.CoCreateInstance(shell.CLSID_KnownFolderManager,None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IKnownFolderManager)
return kf_mgr.GetFolder(folder_id).GetPath()
picture_path = os.path.join(get_known_folder(shell.FOLDERID_Downloads), "Mathe",
"Picture.png")
if os.path.isfile(picture_path):
im = plt.imread(picture_path)
If you're using Windows, that path may cause issues because of the direction of the slashes. Check out this article. You shouldn't hardcode paths because regardless of which direction of slash you use, it can break on other operating systems.
It should work with something like this:
import os
import matplotlib.pyplot as plt
picture_path = os.path.join("C:", "Users", "myusername", "Downloads", "Mathe", "Picture.png")
im = plt.imread(picture_path)

Python import file with dependencies in the same folder

I have a file ref.py that depends on a text file ex.txt, that is in the same directory \home\ref_dir . So it works normally when I run the file ref.py, but if I try to import ref.py to another file work.py in a different directory \home\work_dir , I do the following
import sys
sys.path.append('\home\ref_dir')
import ref
But then I get an error, that the program cannot find ex.txt
How can I solve this issue without using absolute paths. Any ideas?
Use the os module to get access to the current absolute path of the module that you're in, and then get the dirname from that
You would want to open ex.txt in your file like this.
import os
with open('%s/ex.txt' % os.path.dirname(os.path.abspath(__file__)) as ex:
print ex.read()

Categories