- How to print Python installation directory to the output?
- How to print Python installation directory to the output?
- Print Current Directory in Python
- Files and Directories in Python
- Ways to print the current directory in python
- Further reading:
- Conclusion
- How do I find the location of my Python site-packages directory?
- Practical Tips
- Print Contents of PYTHONPATH in Python
- Print Contents of PYTHONPATH in Python
How to print Python installation directory to the output?
In this post, we will see how to print current directory in Python. Files and Directories in Python A computer system uses directories to store and organize files. C:\Users\Username Further reading: Get Parent Directory in Python Read more → Python list files in directory Read more → Using the function to print the current directory in Python
How to print Python installation directory to the output?
Let’s say Python is installed in the location
I want to print this location in the output of my program. Please let me know can I do this.
import sys, os os.path.dirname(sys.executable)
but remember than in Unix systems the «installation» of a program is usually distributed along the following folders:
Maybe either of these will satisfy you:
>>> import sys >>> print(sys.prefix) /usr >>> print(sys.path) ['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>>> import sys >>> print sys.prefix
See the documentation for the sys module for more details.
Dir() function in Python, dir () tries to return a valid list of attributes of the object it is called upon. Also, dir () function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. For Class Objects, it returns a list of names of all the valid attributes and base …
Print Current Directory in Python
In this post, we will see how to print current directory in Python.
Files and Directories in Python
A computer system uses directories to store and organize files. Every file is present in some directory. There is a root folder at the top of the hierarchy, and every directory is a child of this root.
In Python, we have the current directory of a script file. We also have the Current Directory of the Python terminal. At times, both are the same especially when we work with Python notebook files.
Ways to print the current directory in python
We will now discuss how to print the current directory in Python. We will deal with methods and display the directory of the running Python script or the current directory of the Python terminal.
Using the os.getcwd() function to print the current directory in Python
os module that can communicate and interact with the operating system.
The current working directory is the directory in which the Python terminal is operating. At times, it may not be the directory of the Python script.
We can return the current working directory using the os.getcwd() function. It returns the directory as a string.
Using the os.path module to print the current directory in Python
The os.path module provides different pathname-related functions. We can use them to print the current directory in Python.
The __file__ constant will be used in these methods and it represents the pathname of the Python script file. This path is relative to the current working directory. Remember, to use this constant we need to work in a .py file and not on a notebook file.
The os.path.realpath() function from this module can return the path of a given file. It removes any symbolic links present in the path. We can pass the __file__ constant to this function and we will get the path of the file we are working with. We can display this path to print the current directory in Python.
In the above example, we can observe that this method prints the full path and the filename.
We can use the os.path.dirname() function to only print the current directory in Python without the filename. This function accepts a path with a filename and returns the directory.
We can also split the result of the os.path.realpath() function. For this, we will use the os.path.split() function. It splits a given path into two parts. The second part contains the last component of the path and the first part contains everything up to the second part. We can use it to split the path and print the current directory in Python.
Further reading:
Get Parent Directory in Python
Python list files in directory
Using the os.path.abspath() function to print the current directory in Python
This method may not work in all situations so should be used as a last resort. It returns the full pathname of the current file with the specified path. We can provide an empty string (think of it as an empty path), and it will return the path of the current file.
Using the pathlib.Path.cwd() function to print the current directory in Python
Python 3.4 introduces a new efficient library to work with paths and filenames. The pathlib library was introduced to create and work with Path objects that can adapt to different operating systems.
The pathlib.Path class of this library has a variety of functions to work on path-related operations. We can use it to print the current directory in Python. The pathlib.Path.cwd() function can be used to return the current working directory in a pathlib object.
Remember, this method returns the current working directory not the directory of the running file.
Using the pathlib.Path.resolve() function to print the current directory in Python
As discussed, we can work with pathnames with the pathlib.Path objects. We can specify the __file__ constant in the constructor of this class to create a pathlib object.
To get the full path with the filename, we can use the resolve() function. This method will return the full path and remove any symbolic links that occur in the path.
Using the pathlib.Path.parent attribute to print the current directory in Python
The pathlib.Path.parent library returns the parent of the given path. We can use it to remove the filename from the previous method and only print the current directory in Python.
Using the locate.this_dir() function to print the current directory in Python
The locate module can also help to print the current directory in Python. We can use the this_dir() function from this library to return the directory of the current Python script.
Conclusion
This tutorial demonstrated how to print the current directory in Python. To wrap up, we worked with three modules. These were the os , pathlib , and locate modules.
The getcwd() function of the os module returns the current working directory and its submodule os.path has different functions to return the current directory of the file. This module works with Python 2 as well.
We also discussed the pathlib library, which works with Python 3.4 and above. These methods were more efficient as they return pathlib objects with the current directory. The locate.this_dir() function also worked to print the current directory in Python.
THat’s all about how to print current directory in Python.
Was this post helpful?
Python — Get list of files in directory with size, List of files in a directory with size. In this part of the code, we will just get the list of files’ names and sizes. In this code, we have os.stat () function to get the size of each file, and the size will results in ‘byte’ so we have to divide the size of the file from 1024*1024 to get the size in the ‘megabytes’ for a better
How do I find the location of my Python site-packages directory?
How do I find the location of my site-packages directory?
There are two types of site-packages directories, global and per user .
- Global site-packages («dist-packages») directories are listed in sys.path when you run:
python -c 'import site; print(site.getsitepackages())'
Note: With virtualenvs getsitepackages is not available, sys.path from above will list the virtualenv’s site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead:
python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
Practical Tips
- .__path__ lets you identify the location(s) of a specific package: (details)
$ python -c "import setuptools as _; print(_.__path__)" ['/usr/lib/python2.7/dist-packages/setuptools']
$ python3 -c "import os as _; print(_.__file__)" /usr/lib/python3.6/os.py
$ pip show pytest Name: pytest Version: 3.8.2 Summary: pytest: simple powerful testing with Python Home-page: https://docs.pytest.org/en/latest/ Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others Author-email: None License: MIT license Location: /home/peter/.local/lib/python3.4/site-packages Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
>>> import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
(or just first item with site.getsitepackages()[0] )
- outside of virtualenv — provides the path of global site-packages,
- insidue a virtualenv — provides the virtualenv’s site-packages
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
Formatted for readability (rather than use as a one-liner), that looks like the following:
from distutils.sysconfig import get_python_lib print(get_python_lib())
Source: an very old version of «How to Install Django» documentation (though this is useful to more than just Django installation)
python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
It will point you to /usr/lib/pythonX.X/dist-packages
This folder only contains packages your operating system has automatically installed for programs to run.
On ubuntu , the site-packages folder that contains packages installed via setup_tools\easy_install\pip will be in /usr/local/lib/pythonX.X/dist-packages
The second folder is probably the more useful one if the use case is related to installation or reading source code.
If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.
Python — List Files in a Directory, Method 1: Os Module. os.listdir () method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os.listdir () does not return any files or folders. Syntax: os.listdir (path) Parameters: Path of the directory. Return Type: returns a list of …
Print Contents of PYTHONPATH in Python
Whenever we use a module/package in python to use the built-in code, first, we load that module into the memory. The location where the module is located is stored as a path . So whenever we load a module, python finds that module in the list of paths.
The environment variable is one of the sources from where python can find paths to load the modules. PYTHONPATH is an environment variable in which we can set additional paths from where python will find and load packages. It points to the location where our packages are stored. We set paths in it whenever we don’t want to install extra packages in the default storage directory of python. In that case, we store the modules in some other directory and save the path of that directory in the PYTHONPATH variable.
Print Contents of PYTHONPATH in Python
Before printing the contents of PYTHONPATH , we must ensure that the PYTHONPATH variable exists in our environment variables and contains our specified paths. If the PYTHONPATH variable is not set, we will get KeyError: ‘PYTHONPATH’ .
Now, if the PYTHONPATH variable is set and we want to print the contents of it. We will write the following lines of code to get the lists of paths stored in that variable. The output on each computer might differ depending on the paths stored in the variable.
If multiple paths exist in that variable, we can split the returned string based on the path separator symbol i-e semi-colon ( ; ).
import os print('List of paths in PYTHONPATH:',os.environ['PYTHONPATH'])
List of paths in PYTHONPATH: /home/user/mypackages
I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.