Python - Directory

1 - About

3 - Properties

3.1 - name

To get the directory name, it depends of the path type.

If this is:

  • file usesdirname. It returns the second element

dirname=os.path.dirname("/backup/remote_url.csv")
dirname


/backup

  • directory uses basename. it returns the first element

dirname=os.path.basename("/backup")
dirname


backup

4 - Management

4.1 - Working

File System - (Current|Working) Directory (cwd) in Python


import os
pwd = os.getcwd()

4.2 - Exists


os.path.exists(directory)

4.3 - Create


os.makedirs(directory)

4.4 - Listing

4.4.1 - One level


import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

4.4.2 - Recursive / Traversal


import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap