Python - Directory

About

Properties

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

Management

Working

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

import os
pwd = os.getcwd()

Exists

os.path.exists(directory)

Create

os.makedirs(directory)

Listing

One level

import os

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

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

Powered by ComboStrap