Using os

https://docs.python.org/3/library/os.html

https://docs.python.org/3/library/os.path.html

INTRODUCTION

OS module provides various functions to interact with the operating system. Programs that import and use 'os' stand a better chance of being portable between different platforms. Programs should leave all pathname manipulation to 'os.path' (e.g., split and join).


import os

# current working directory 
current = os.getcwd()   # '/home/andrzej' in Linux Debian

# Using join().
# parent directory 
print(os.pardir)   # ".." in UNIX
parent = os.path.join(current, os.pardir)   # '/home/andrzej/..'
# Join two or more pathname components, inserting os.sep as needed.

print(current + os.sep + os.pardir)   # the same
print(os.path.abspath(parent))   # '/home', the absolute path
print(os.path.relpath(parent))   # '..' the relative path

# Using split().

path = '/home/andrzej/Pobrane'
print(os.path.exists(path))   # True
print(os.path.isabs(path))   # True, it is the absolute path
print(os.path.isfile(path))   # False
print(os.path.isdir(path))   # True
print(os.path.getsize(path))   # the number of bytes

print(os.path.split(path))   # ('/home/andrzej', 'Pobrane')
# Split a pathname.  Returns tuple "(head, tail)" where "tail" is
# everything after the final slash.  Either part may be empty.

print(os.path.basename(path))   # 'Pobrane'
print(os.path.dirname(path))   # '/home/andrzej'

# Create a directory.

dirname = "MyWork"
print(os.path.isdir(dirname))   # False
os.mkdir(dirname)
print(os.path.isdir(dirname))   # True
print(os.path.abspath(dirname))   # '/home/andrzej/MyWork'
os.rmdir(dirname)   # a directory have to be empty
os.listdir(dirname)   # return a list containing the names of the files in the directory

# Create directory and all intermediate directories if don't exists.
dirname = "A/B/C"
if not os.path.exists(dirname):
    os.makedirs(dirname)

# File tools.

os.chmod(path, mode)   # change the access permissions of a file
os.chmod('spam.txt', 0777)   # enabled all accesses (octal 0777 means bits 111 111 111)
os.chown(path, uid, gid)   # hange the owner and group id of path to the numeric uid and gid
os.remove(path)   # remove a file
os.rename(old_name, new_name)   # rename a file or directory
os.listdir(path)   # return a list containing the names of the files

os.popen(cmd)
# It runs a shell command string and give us a file object
# from which we can read the command's output.
# 'cmd' is a platform-specific command.

os.popen('ls').readlines()   # ['Dokumenty\n', 'Mail\n', 'Muzyka\n', 'Obrazy\n', 'Pobrane\n']
os.popen('ls *.html').readlines()

os.system(cmd)   # execute the command in a subshell

EXAMPLES


# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/',
# it could delete all your disk files.

import os

for root, dirs, files in os.walk(top, topdown=False):   # walking bottom-up
    # 'root' is a string, the path to the directory
    # 'dirs' is a list of the names of the subdirectories in 'root'
    # 'files' is a list of the names of the non-directory files in 'root'
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

# Display the number of bytes taken by non-directory files in each directory
# under the starting directory ('top'). Skip any CVS subdirectory.

import os

for root, dirs, files in os.walk(top):   # walking top-down (default)
    print(root, "consumes", end=" ")
    print(sum(os.path.getsize(os.path.join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

# For a given directory find the number of PDF files in the directory tree
# (".pdf" extensions).

import os

n_pdf = 0   # the number of PDF files
for root, dirs, files in os.walk(top):   # walking top-down (default)
    for name in files:
        #if name[-4:] == ".pdf":
        #if name.endswith(".pdf"):
        if name.lower().endswith(".pdf"):   # for *.PDF files
            n_pdf += 1

print("The number of PDF files in {} directory is {}".format(top, n_pdf))