.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/builtin_modules/_os.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_builtin_modules__os.py: ======== 2.1 os ======== .. important:: This lesson is still under development. When python is installed, several modules/packages are pre-installed in it. These modules provide some very basic functionality to the user. The ``os`` is such a built-in module which provides the functionalities about paths or operating system. .. GENERATED FROM PYTHON SOURCE LINES 13-17 .. code-block:: default import os .. GENERATED FROM PYTHON SOURCE LINES 18-28 system() ======== It is used to execute commands that we would otherwise execute using command prompt on windows or on terminal. For example on Windows we can do ``os.system(dir)`` where ``dir`` is a command for Windows command prompt .. code-block:: python os.system(dir) .. GENERATED FROM PYTHON SOURCE LINES 30-33 getcwd() ======== It returns the current working directory. .. GENERATED FROM PYTHON SOURCE LINES 33-35 .. code-block:: default print(os.getcwd()) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules .. GENERATED FROM PYTHON SOURCE LINES 36-38 .. code-block:: default print(type(os.getcwd())) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 39-45 path ===== The ``path`` submodule of ``os`` module contains several helpful functions to manipulate path. Find out whether the path `p` exists or not .. GENERATED FROM PYTHON SOURCE LINES 45-48 .. code-block:: default p = os.getcwd() os.path.isdir(p) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 49-50 Find out whther `p` is a file or not .. GENERATED FROM PYTHON SOURCE LINES 50-52 .. code-block:: default os.path.isfile(p) .. rst-class:: sphx-glr-script-out .. code-block:: none False .. GENERATED FROM PYTHON SOURCE LINES 53-54 --- .. GENERATED FROM PYTHON SOURCE LINES 54-58 .. code-block:: default # Find the parent directory of `p`. os.path.dirname(p) .. rst-class:: sphx-glr-script-out .. code-block:: none '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts' .. GENERATED FROM PYTHON SOURCE LINES 59-60 --- .. GENERATED FROM PYTHON SOURCE LINES 60-63 .. code-block:: default os.path.abspath(p) .. rst-class:: sphx-glr-script-out .. code-block:: none '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules' .. GENERATED FROM PYTHON SOURCE LINES 64-65 ---- .. GENERATED FROM PYTHON SOURCE LINES 65-68 .. code-block:: default os.path.split(p) .. rst-class:: sphx-glr-script-out .. code-block:: none ('/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts', 'builtin_modules') .. GENERATED FROM PYTHON SOURCE LINES 69-70 --- .. GENERATED FROM PYTHON SOURCE LINES 70-72 .. code-block:: default os.path.basename(p) .. rst-class:: sphx-glr-script-out .. code-block:: none 'builtin_modules' .. GENERATED FROM PYTHON SOURCE LINES 73-74 --- .. GENERATED FROM PYTHON SOURCE LINES 74-77 .. code-block:: default os.path.exists(p) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 78-81 remove() --------- delete a file from disk .. GENERATED FROM PYTHON SOURCE LINES 83-85 replace() ========= .. GENERATED FROM PYTHON SOURCE LINES 88-91 listdir ======= Returns a list of folders/directories in a given path. .. GENERATED FROM PYTHON SOURCE LINES 91-93 .. code-block:: default os.listdir(p) .. rst-class:: sphx-glr-script-out .. code-block:: none ['readme.txt', '_os.py', '_types_typing.py', '_csv.py', '_warnings.py', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', '_copy.py', '_collections.py', '_itertools.py', '_math.py'] .. GENERATED FROM PYTHON SOURCE LINES 94-96 environ ======= .. GENERATED FROM PYTHON SOURCE LINES 96-101 .. code-block:: default environ = os.environ print(environ) print(type(environ)) print(len(environ)) .. rst-class:: sphx-glr-script-out .. code-block:: none environ({'READTHEDOCS_VIRTUALENV_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/envs/dev', 'READTHEDOCS_CANONICAL_URL': 'https://python-seekho.readthedocs.io/en/dev/', 'HOSTNAME': 'build-26236814-project-717928-python-seekho', 'READTHEDOCS_GIT_CLONE_URL': 'https://github.com/AtrCheema/python-seekho.git', 'HOME': '/home/docs', 'NO_COLOR': '1', 'READTHEDOCS': 'True', 'READTHEDOCS_PRODUCTION_DOMAIN': 'readthedocs.org', 'READTHEDOCS_REPOSITORY_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev', 'READTHEDOCS_PROJECT': 'python-seekho', 'READTHEDOCS_OUTPUT': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/_readthedocs/', 'PATH': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/envs/dev/bin:/home/docs/.asdf/shims:/home/docs/.asdf/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'READTHEDOCS_VERSION_TYPE': 'branch', 'LANG': 'C.UTF-8', 'READTHEDOCS_LANGUAGE': 'en', 'DEBIAN_FRONTEND': 'noninteractive', 'READTHEDOCS_GIT_COMMIT_HASH': 'ebaff922615a23925da260d6ea0b38c967ed6ee6', 'READTHEDOCS_VERSION_NAME': 'dev', 'READTHEDOCS_VERSION': 'dev', 'PWD': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/docs/source', 'READTHEDOCS_GIT_IDENTIFIER': 'dev', 'DOCUTILSCONFIG': '/home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/docs/source/docutils.conf'}) 22 .. GENERATED FROM PYTHON SOURCE LINES 102-104 wait() ======= .. GENERATED FROM PYTHON SOURCE LINES 106-108 rename() ========= .. GENERATED FROM PYTHON SOURCE LINES 110-112 renames() ========= .. GENERATED FROM PYTHON SOURCE LINES 114-117 mkdir() ======== creates a directory if all its upper/parent directories are present. .. GENERATED FROM PYTHON SOURCE LINES 117-124 .. code-block:: default new_folder = os.path.join(os.getcwd(), "NewFolder") print(os.path.exists(new_folder)) os.mkdir(new_folder) print(os.path.exists(new_folder)) .. rst-class:: sphx-glr-script-out .. code-block:: none False True .. GENERATED FROM PYTHON SOURCE LINES 125-129 .. code-block:: default p = os.path.join(os.getcwd(), "NonExistentFolder", "InsideNonExistentFolder") print(os.path.exists(p)) .. rst-class:: sphx-glr-script-out .. code-block:: none False .. GENERATED FROM PYTHON SOURCE LINES 130-131 uncomment following line .. GENERATED FROM PYTHON SOURCE LINES 131-134 .. code-block:: default # os.mkdir(p) # FileNotFoundError .. GENERATED FROM PYTHON SOURCE LINES 135-137 os.makedirs =========== .. GENERATED FROM PYTHON SOURCE LINES 137-140 .. code-block:: default os.makedirs(p) print(os.path.exists(p)) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 141-143 rmdir() ========= .. GENERATED FROM PYTHON SOURCE LINES 143-148 .. code-block:: default print(os.path.exists(new_folder)) os.rmdir(new_folder) print(os.path.exists(new_folder)) .. rst-class:: sphx-glr-script-out .. code-block:: none True False .. GENERATED FROM PYTHON SOURCE LINES 149-152 cpu_count() =========== Cound the number of cpus/cores/processes available. .. GENERATED FROM PYTHON SOURCE LINES 152-155 .. code-block:: default print(os.cpu_count()) .. rst-class:: sphx-glr-script-out .. code-block:: none 2 .. GENERATED FROM PYTHON SOURCE LINES 156-158 chdir() ======== .. GENERATED FROM PYTHON SOURCE LINES 158-168 .. code-block:: default original_wd = os.getcwd() print("Current working directory is \n", original_wd) print(f"It has {len(os.listdir(os.getcwd()))} sub-directories/folders in it.") new_wd = os.path.join(os.path.dirname(original_wd)) os.chdir(new_wd) print("Now we have changed working directory to \n", new_wd) print(f"This new directory has {len(os.listdir(os.getcwd()))} sub-directories/folders in it") # now changing back to original os.chdir(original_wd) .. rst-class:: sphx-glr-script-out .. code-block:: none Current working directory is /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules It has 14 sub-directories/folders in it. Now we have changed working directory to /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts This new directory has 8 sub-directories/folders in it .. GENERATED FROM PYTHON SOURCE LINES 169-171 walk ==== .. GENERATED FROM PYTHON SOURCE LINES 171-174 .. code-block:: default for dirpath, dirnames, filenames in os.walk(os.getcwd()): print(dirpath, dirnames, filenames) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules ['NonExistentFolder'] ['readme.txt', '_os.py', '_types_typing.py', '_csv.py', '_warnings.py', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', '_copy.py', '_collections.py', '_itertools.py', '_math.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules/NonExistentFolder ['InsideNonExistentFolder'] [] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules/NonExistentFolder/InsideNonExistentFolder [] [] .. GENERATED FROM PYTHON SOURCE LINES 175-179 .. code-block:: default python_seekho_scripts = os.path.join(os.path.dirname((os.path.abspath('')))) for dirpath, dirnames, filenames in os.walk(python_seekho_scripts): print(dirpath, dirnames, filenames) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts ['numpy', 'basics', 'advanced', 'oop', 'pandas', 'builtin_modules', 'plotting'] ['readme.txt'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/numpy [] ['readme.txt', 'stack_vs_concatenate.py', 'dimensions_axis.py', 'digitize.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/basics [] ['nested_functions.py', 'for_loops.py', 'installing_packages.py', 'conditional_statements.py', 'copying_lists.py', 'args_and_kwargs.py', 'readme.txt', 'exceptions.py', 'lists.py', 'while_loops.py', 'dictionaries.py', 'generators.py', 'NewFile.json', 'functions.py', 'iterator_vs_iterable.py', 'variables.py', 'operators.py', 'sets.py', 'io_operations.py', 'global_vs_local.py', 'sequential_data.py', 'NewFile', 'keywords.py', 'print_function.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/advanced [] ['reg_expressions.py', 'daily_q.csv', 'readme.txt', 'interfacing_with_fortran.py', 'parallel_processing.py', 'interfacing_with_c_cpp.py', 'unit_testing.py', 'read_csv_gpt.cpp', 'interfacing_with_matlab.py', 'interfacing_with_cpp.py', 'speeding_up_with_numba.py', 'scripts_to_executables.py', '_cython.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/oop [] ['class.py', '__getattr__.py', 'readme.txt', 'init.py', 'inheritance.py', 'call.py', 'class_vs_instance_attributes.py', 'attributes.py', 'str_repr.py', 'class_methods.py', 'introduction.py', 'public_vs_private_attributes.py', 'magical_methods.py', 'methods.py', 'static_methods.py', 'getattr_setattr.py', 'descriptors.py', 'property.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/pandas [] ['speeding_up.py', 'readme.txt', 'apply.py', 'pivot_vs_melt.py', 'multi-indexing.py', 'groupby.py', 'working_with_timeseries.py', 'dataframe_vs_series.py', 'io.py', 'indexing_vs_slicing.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules ['NonExistentFolder'] ['readme.txt', '_os.py', '_types_typing.py', '_csv.py', '_warnings.py', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', '_copy.py', '_collections.py', '_itertools.py', '_math.py'] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules/NonExistentFolder ['InsideNonExistentFolder'] [] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/builtin_modules/NonExistentFolder/InsideNonExistentFolder [] [] /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/dev/scripts/plotting [] ['_bar.py', 'readme.txt', '_plot.py', '_contour.py', 'marginal_plots.py', '_scatter.py', '_circular_bar.py', '_parallel_plot.py', 'intro.py', '_hist.py', '_dumbell.py', '_regplot.py', '_lollipop.py', '_ridge.py', '_boxplot.py', 'pie.py', '_taylor.py', '_violin.py', '_imshow.py', '_spider.py'] .. GENERATED FROM PYTHON SOURCE LINES 180-183 finding files ============= Let's create few files first. .. GENERATED FROM PYTHON SOURCE LINES 183-191 .. code-block:: default for i in range(5): with open(f'TextFile_{i}.txt', 'w'): pass for i in range(5): with open(f'CsvFile_{i}.csv', 'w'): pass .. GENERATED FROM PYTHON SOURCE LINES 192-193 If we want to find all files and folders within a specific path .. GENERATED FROM PYTHON SOURCE LINES 193-198 .. code-block:: default path_to_look = os.getcwd() print(os.listdir(path_to_look)) .. rst-class:: sphx-glr-script-out .. code-block:: none ['NonExistentFolder', 'TextFile_1.txt', 'CsvFile_0.csv', 'readme.txt', 'TextFile_4.txt', '_os.py', 'CsvFile_4.csv', '_types_typing.py', 'CsvFile_1.csv', '_csv.py', 'CsvFile_2.csv', '_warnings.py', 'TextFile_2.txt', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', 'CsvFile_3.csv', 'TextFile_0.txt', '_copy.py', '_collections.py', '_itertools.py', '_math.py', 'TextFile_3.txt'] .. GENERATED FROM PYTHON SOURCE LINES 199-201 If we want to find only files and not folders/directories, we can do following list comprehension. .. GENERATED FROM PYTHON SOURCE LINES 201-204 .. code-block:: default print([f for f in os.listdir(path_to_look) if os.path.isfile(f)]) .. rst-class:: sphx-glr-script-out .. code-block:: none ['TextFile_1.txt', 'CsvFile_0.csv', 'readme.txt', 'TextFile_4.txt', '_os.py', 'CsvFile_4.csv', '_types_typing.py', 'CsvFile_1.csv', '_csv.py', 'CsvFile_2.csv', '_warnings.py', 'TextFile_2.txt', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', 'CsvFile_3.csv', 'TextFile_0.txt', '_copy.py', '_collections.py', '_itertools.py', '_math.py', 'TextFile_3.txt'] .. GENERATED FROM PYTHON SOURCE LINES 205-206 If we want to find files with a specific extension, we can do as following .. GENERATED FROM PYTHON SOURCE LINES 206-209 .. code-block:: default print([f for f in os.listdir(path_to_look) if os.path.isfile(f) and f.endswith(".txt")]) .. rst-class:: sphx-glr-script-out .. code-block:: none ['TextFile_1.txt', 'readme.txt', 'TextFile_4.txt', 'TextFile_2.txt', 'TextFile_0.txt', 'TextFile_3.txt'] .. GENERATED FROM PYTHON SOURCE LINES 210-212 If we want to find files with a specific extension, and starting with a specific name, we can do as following .. GENERATED FROM PYTHON SOURCE LINES 212-214 .. code-block:: default print([f for f in os.listdir(path_to_look) if os.path.isfile(f) and f.endswith(".txt") and f.startswith('TextFile_')]) .. rst-class:: sphx-glr-script-out .. code-block:: none ['TextFile_1.txt', 'TextFile_4.txt', 'TextFile_2.txt', 'TextFile_0.txt', 'TextFile_3.txt'] .. GENERATED FROM PYTHON SOURCE LINES 215-216 number of lessons in python-seekho book .. GENERATED FROM PYTHON SOURCE LINES 216-219 .. code-block:: default scripts = [fname for f in os.walk(python_seekho_scripts) for fname in f[2] if fname.endswith('.py')] print(scripts) .. rst-class:: sphx-glr-script-out .. code-block:: none ['stack_vs_concatenate.py', 'dimensions_axis.py', 'digitize.py', 'nested_functions.py', 'for_loops.py', 'installing_packages.py', 'conditional_statements.py', 'copying_lists.py', 'args_and_kwargs.py', 'exceptions.py', 'lists.py', 'while_loops.py', 'dictionaries.py', 'generators.py', 'functions.py', 'iterator_vs_iterable.py', 'variables.py', 'operators.py', 'sets.py', 'io_operations.py', 'global_vs_local.py', 'sequential_data.py', 'keywords.py', 'print_function.py', 'reg_expressions.py', 'interfacing_with_fortran.py', 'parallel_processing.py', 'interfacing_with_c_cpp.py', 'unit_testing.py', 'interfacing_with_matlab.py', 'interfacing_with_cpp.py', 'speeding_up_with_numba.py', 'scripts_to_executables.py', '_cython.py', 'class.py', '__getattr__.py', 'init.py', 'inheritance.py', 'call.py', 'class_vs_instance_attributes.py', 'attributes.py', 'str_repr.py', 'class_methods.py', 'introduction.py', 'public_vs_private_attributes.py', 'magical_methods.py', 'methods.py', 'static_methods.py', 'getattr_setattr.py', 'descriptors.py', 'property.py', 'speeding_up.py', 'apply.py', 'pivot_vs_melt.py', 'multi-indexing.py', 'groupby.py', 'working_with_timeseries.py', 'dataframe_vs_series.py', 'io.py', 'indexing_vs_slicing.py', '_os.py', '_types_typing.py', '_csv.py', '_warnings.py', '_random_module.py', '_time.py', '_pathlib.py', '_sys.py', '_copy.py', '_collections.py', '_itertools.py', '_math.py', '_bar.py', '_plot.py', '_contour.py', 'marginal_plots.py', '_scatter.py', '_circular_bar.py', '_parallel_plot.py', 'intro.py', '_hist.py', '_dumbell.py', '_regplot.py', '_lollipop.py', '_ridge.py', '_boxplot.py', 'pie.py', '_taylor.py', '_violin.py', '_imshow.py', '_spider.py'] .. GENERATED FROM PYTHON SOURCE LINES 220-223 .. code-block:: default print(f"Total number of lessons in python-seekho book are {len(scripts)}.") .. rst-class:: sphx-glr-script-out .. code-block:: none Total number of lessons in python-seekho book are 91. .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.012 seconds) .. _sphx_glr_download_auto_examples_builtin_modules__os.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/builtin_modules/_os.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: _os.py <_os.py>` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: _os.ipynb <_os.ipynb>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_