Python - Directory

Card Puncher Data Processing

About

File System - Directory in Python

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

What is the working or current directory ? 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')





Discover More
Card Puncher Data Processing
Python - File System

File system in python A file or a directory location is defined by a path See



Share this page:
Follow us:
Task Runner