How to delete files in python

Hi…to all today i learnt how to delete files in python..here the codes

import os
os.remove("Myfilename.txt")


suppose if you want to delete all the file named myfile1.txt,myfile2.txt…it goes on like this.. we can use myfile*.txt  to delete all those files..here the code for this

 

import os,glob
for filePath in glob.glob("Mydirectory/Myfile*.txt")
      if os.filePath.isfile(filePath):
         os.remove(filePath)

if you want to delete all the files in subdirectories you can use the following code

import os, glob
 
for root, dirs, files in os.walk('MyDirectory'):
    for filePath in glob.glob(os.path.join(root, "MyFile*.txt")):
        if os.path.isfile(filePath):
            os.remove(filePath)

it is possible to delete files you didn’t intend to. So make sure you test thoroughly before implementing code like this..

Thats it…thanks….happy coding with python…:)

Author: Balaji

Hi..My name is Balaji and i am working as a Senior Software Developer in India. I am interested in Shell scripts, python, erlang , linux kernel .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: