Home » Python

Python | Remove an existing file (Example of os.remove() method)

os.remove() method in python: Here, we are going to learn how to remove an existing file in python?
Submitted by IncludeHelp, on December 30, 2018

Removing an existing file

To remove/delete an existing file – we use "remove()" method of "os" module – so to access the "remove()" method, we must have to import the module "os".

Module import statement: import os

Syntax of remove() method: os.remove(file_name)

Here, file_name is the name of an existing file.

Example 1 (removing an existing file):

import os

def main():
    
    fo = open("data.txt","wt") # creating a file
    fo.write("Hello") # writing the content 
    fo.close() # closing the file 
    
    # checking if file exists or not?
    if os.path.exists("data.txt"):
        print("data.txt exists...")
    else:
        print("data.txt doe not exist...")

    # removing the file
    os.remove("data.txt")
    # checking if file exists or not?
    if os.path.exists("data.txt"):
        print("data.txt exists...")
    else:
        print("data.txt doe not exist...")    
    
if __name__=="__main__":main()

Output

data.txt exists...
data.txt doe not exist...

Example 2 (Trying to remove a file that does not exist):

import os

def main():    
    # removing the that does not exist
    os.remove("abc.txt")
if __name__=="__main__":main()

Output

Traceback (most recent call last)
  File "/home/main.py", line 8, in <module>
    if __name__=="__main__":main()
  File "/home/main.py", line 6, in main
    os.remove("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

Example 3 (Handling "FileNotFoundError" Exception)

import os

def main():
    try:
        # removing the that does not exist
        os.remove("abc.txt")
    except FileNotFoundError:
        print("ERROR: abc.txt does not exist...")
    except:
        print("Unknown error...")
    
if __name__=="__main__":main()

Output

ERROR: abc.txt does not exist...






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.