🐍
Python For Starters
  • Overview
  • Python for starters
  • Content
  • Foreword
  • Introduction To Python
    • Python Installation
    • Variables
    • Python Data Types
    • Python Data Structures
    • Python numbers
    • Python strings
    • Python Boolean
    • Python constants
    • Python Comments
    • Type Conversion
    • Control flow in python
  • Python Functions
    • Function Definition
    • Function Parameter
    • Recursive Functions
    • Using Global Variables in Functions
    • Lambda Functions
  • What are Data Structures
    • Python Lists
    • Python Tuples
    • Python Dictionaries
    • Python Sets
    • Iterable in python
    • Python Map, Filter & Reduce Functions
  • Error handling in Python
  • Loop ... Else Clause, Partial Functions & Type Hints
    • Partial Functions
    • Type Hints
  • Python Modules
  • Python Libraries & Packages
    • Python Packages
  • Directory & IO
    • Python IO Module
  • Pyenv
  • Virtual Environments
    • Pipenv
    • Virtualenv
  • Object Oriented Programming in Python
    • Class
    • Class Methods
    • Python Class Inheritance
    • Python Class Polymorphism
    • Python special methods
  • Appendix
  • Contributing
Powered by GitBook
On this page

Directory & IO

Working with Directories

In Python, you can use the os module to work with directories (also called "folders"). The os module provides functions to perform various operations on directories.

Here are a few examples of common tasks you might perform with the os module:

Creating a Directory

To create a new directory, you can use the os.mkdir() function. This function takes a single argument, which is the name of the directory you want to create.

import os

# Create a new directory called "newdir"
os.mkdir("emmanuella")

Changing the Current Working Directory

To change the current working directory, you can use the os.chdir() function. This function takes a single argument, which is the path of the directory you want to change to.

import os

# Change the current working directory to "newdir"
os.chdir("emmanuella")

Listing the Contents of a Directory

To list the contents of a directory, you can use the os.listdir() function. This function takes a single argument, which is the path of the directory you want to list the contents of. It returns a list of the names of the files and directories in that directory.

import os

# List the contents of the current working directory
contents = os.listdir()
print(contents)

Checking if a Path is a Directory

To check if a given path is a directory, you can use the os.path.isdir() function. This function takes a single argument, which is the path you want to check. It returns True if the path is a directory, and False if it is not.

import os

# Check if the current working directory is a directory
is_dir = os.path.isdir(".")
print(is_dir)
PreviousPython PackagesNextPython IO Module

Last updated 2 years ago