How to delete a file in Python

0 min read 138 words

A quick solution in Python

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

The above code will delete a file in Python, it will not however delete a directory, or a directory containing files. For this we will need to explore a bit more..

Check file exists before deleting

First check if the file exists before deleting it:

import os

if os.path.exists("filename.txt"):
  os.remove("filename.txt")
else:
  print("The file doesn't exist")

Delete a directory/folder

Sometimes you may want to delete an entire folder as well:

import os
os.rmdir("foldername")

What options are available?

#removes a file.
os.remove()

#removes an empty directory.
os.rmdir()

#deletes a directory and all its contents.
shutil.rmtree()

Using Pathlib as an alternative

As of Python 3.4+, you can also use pathlib as follows:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

rmdir is also available to remove a blank directory:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags