Nearby lessons

92 of 159

Python - Delete Files

📌 What You Will Learn
  • Check whether a file exists using os.path.isfile()
  • Delete a file using os.remove()
  • Avoid FileNotFoundError by checking existence before deletion
  • Understand the os module functions used for file operations
  • Count the lines, words, and characters of a text file

Checking Whether a File Exists

Before performing operations on a file, it is a good programming practice to check whether the file exists.

If we try to open a file that does not exist in read (r) mode, Python raises a FileNotFoundError.

To avoid this error, Python provides the os.path.isfile() function.

The os.path.isfile() Function

The os.path.isfile() function checks whether the specified file exists.

  • Returns True if the specified file exists.
  • Returns False if the file does not exist.
Loading editor…

Example: Checking File Existence

Loading editor…

Sample Output (File Exists)

Sample Output (File Does Not Exist)

Deleting a File

To delete an existing file, Python provides the os.remove() function.

If the file does not exist, os.remove() raises FileNotFoundError.

Loading editor…

Example: Delete a File

Loading editor…

Explanation

The os.remove("abc.txt") statement permanently deletes the file abc.txt from the filesystem.

Once deleted, the file cannot be recovered with a normal file operation.

Safe Deletion Program

The following program deletes a file only when it exists, avoiding FileNotFoundError.

Loading editor…

Sample Output

Explanation

  • os.path.isfile(fname) checks whether the file exists.
  • If it exists, os.remove(fname) deletes it.
  • If it does not exist, the program prints a friendly message instead of crashing.

Program: Count Lines, Words and Characters

The following program reads a text file and counts the total number of lines, words, and characters.

Loading editor…

Sample Output

Explanation

  • Three counters (lcount, wcount, ccount) are initialized to zero.
  • The for line in f loop reads one line at a time, which is memory efficient for large files.
  • line.split() separates the line into individual words.
  • len(line) returns the number of characters in the current line.

Deleting Files vs Removing Directories

Function Purpose
os.remove() Deletes a file.
os.rmdir() Removes an empty directory.
📝 Key Takeaways
  • os.path.isfile(filename) returns True if the file exists and False otherwise
  • os.remove(filename) deletes a file permanently
  • Always check that a file exists before trying to delete it
  • Deleting a non-existent file raises FileNotFoundError
  • os.remove() deletes files, while os.rmdir() removes empty directories

🧠 Test Your Knowledge

7 Questions
Progress: 0 / 7

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.