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.
🐍Code Cell
1import os
2 
3os.path.isfile(filename)
Output
No output captured.

Example: Checking File Existence

🐍Code Cell
1import os
2 
3fname = input("Enter File Name: ")
4 
5if os.path.isfile(fname):
6 print("File exists")
7else:
8 print("File does not exist")
Output
No output captured.

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.

🐍Code Cell
1import os
2 
3os.remove(filename)
Output
No output captured.

Example: Delete a File

🐍Code Cell
1import os
2 
3os.remove("abc.txt")
4 
5print("abc.txt deleted successfully")
Output
abc.txt deleted successfully

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.

🐍Code Cell
1import os
2 
3fname = input("Enter File Name: ")
4 
5if os.path.isfile(fname):
6 os.remove(fname)
7 print(fname, "deleted successfully")
8else:
9 print(fname, "does not exist")
Output
No output captured.

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.

🐍Code Cell
1import os
2 
3fname = input("Enter File Name: ")
4 
5if os.path.isfile(fname):
6 
7 f = open(fname, "r")
8 
9 lcount = wcount = ccount = 0
10 
11 for line in f:
12 
13 lcount = lcount + 1
14 
15 words = line.split()
16 
17 wcount = wcount + len(words)
18 
19 ccount = ccount + len(line)
20 
21 print("The Number of Lines:", lcount)
22 print("The Number of Words:", wcount)
23 print("The Number of Characters:", ccount)
24 
25 f.close()
26 
27else:
28 print("File does not exist")
Output
No output captured.

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