Python Directory and Files Management (With Examples) (2024)

A directory is a collection of files and subdirectories. A directory inside a directory is known as a subdirectory.

Python has the os module that provides us with many useful methods to work with directories (and files as well).

Get Current Directory in Python

We can get the present working directory using the getcwd() method of the os module.

This method returns the current working directory in the form of a string. For example,

import osprint(os.getcwd())# Output: C:\Program Files\PyScripter

Here, getcwd() returns the current directory in the form of a string.

Changing Directory in Python

In Python, we can change the current working directory by using the chdir() method.

The new path that we want to change into must be supplied as a string to this method. And we can use both the forward-slash / or the backward-slash \ to separate the path elements.

Let's see an example,

import os# change directoryos.chdir('C:\\Python33')print(os.getcwd())Output: C:\Python33

Here, we have used the chdir() method to change the current working directory and passed a new path as a string to chdir().

List Directories and Files in Python

All files and sub-directories inside a directory can be retrieved using the listdir() method.

This method takes in a path and returns a list of subdirectories and files in that path.

If no path is specified, it returns the list of subdirectories and files from the current working directory.

import osprint(os.getcwd())C:\Python33# list all sub-directoriesos.listdir()['DLLs','Doc','include','Lib','libs','LICENSE.txt','NEWS.txt','python.exe','pythonw.exe','README.txt','Scripts','tcl','Tools']os.listdir('G:\\')['$RECYCLE.BIN','Movies','Music','Photos','Series','System Volume Information']

Making a New Directory in Python

In Python, we can make a new directory using the mkdir() method.

This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.

os.mkdir('test')os.listdir()['test']

Renaming a Directory or a File

The rename() method can rename a directory or a file.

For renaming any directory or file, rename() takes in two basic arguments:

  • the old name as the first argument
  • the new name as the second argument.

Let's see an example,

import osos.listdir()['test']# rename a directoryos.rename('test','new_one')os.listdir()['new_one']

Here, 'test' directory is renamed to 'new_one' using the rename() method.

Removing Directory or File in Python

In Python, we can use the remove() method or the rmdir() method to remove a file or directory.

First let's use remove() to delete a file,

import os# delete "myfile.txt" fileos.remove("myfile.txt")

Here, we have used the remove() method to remove the "myfile.txt" file.

Now let's use rmdir() to delete an empty directory,

import os# delete the empty directory "mydir"os.rmdir("mydir") 

In order to remove a non-empty directory, we can use the rmtree() method inside the shutil module. For example,

import shutil# delete "mydir" directory and all of its contentsshutil.rmtree("mydir")

It's important to note that these functions permanently delete the files or directories, so we need to careful when using them.

Also Read:

Python Directory and Files Management (With Examples) (2024)
Top Articles
The Blessing of Giving: Educating Your Church on the Spiritual and Practical Benefits of Tithing
Which Bank of America branches are closing soon in California?
Sdn Md 2023-2024
Noaa Charleston Wv
Aadya Bazaar
Phone Number For Walmart Automotive Department
Craigslist Free Stuff Appleton Wisconsin
Poe Pohx Profile
Craigslist Nj North Cars By Owner
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Lenscrafters Huebner Oaks
6001 Canadian Ct Orlando Fl
About Us | TQL Careers
Painting Jobs Craigslist
Snow Rider 3D Unblocked Wtf
Pokemon Unbound Shiny Stone Location
Shiftselect Carolinas
Gazette Obituary Colorado Springs
Inbanithi Age
Craig Woolard Net Worth
Suspiciouswetspot
Webworx Call Management
Scott Surratt Salary
Jackass Golf Cart Gif
Delta Math Login With Google
Parent Management Training (PMT) Worksheet | HappierTHERAPY
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Skip The Games Ventura
The Complete Guide To The Infamous "imskirby Incident"
Empire Visionworks The Crossings Clifton Park Photos
Skill Boss Guru
The Holdovers Showtimes Near Regal Huebner Oaks
Frommer's Philadelphia & the Amish Country (2007) (Frommer's Complete) - PDF Free Download
2007 Peterbilt 387 Fuse Box Diagram
Gregory (Five Nights at Freddy's)
Courses In Touch
Academic Calendar / Academics / Home
Garland County Mugshots Today
Catchvideo Chrome Extension
Trending mods at Kenshi Nexus
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
How the Color Pink Influences Mood and Emotions: A Psychological Perspective
Zipformsonline Plus Login
The Blackening Showtimes Near Ncg Cinema - Grand Blanc Trillium
Random Warzone 2 Loadout Generator
Shannon Sharpe Pointing Gif
Sams La Habra Gas Price
Besoldungstabellen | Niedersächsisches Landesamt für Bezüge und Versorgung (NLBV)
Koniec veľkorysých plánov. Prestížna LEAF Academy mení adresu, masívny kampus nepostaví
Heisenberg Breaking Bad Wiki
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6328

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.