How To Delete A File In Python

Pavol Kutaj
Sep 17, 2021

The aim of this how-to-guide🏁 is to delete a file in python.

notes

  1. import os module
  2. be explicit and include try/except block (EAFP style of exception handling)
  3. use os.remove(<filename>) method

example

import os
myfile= raw_input("Enter file name to delete: ")
try:
os.remove(myfile)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))

links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com