Nearby lessons
92 of 159Python - Delete Files
- 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
Trueif the specified file exists. - Returns
Falseif the file does not exist.
Example: Checking File Existence
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.
Example: Delete a File
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.
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.
Sample Output
Explanation
- Three counters (
lcount,wcount,ccount) are initialized to zero. - The
for line in floop 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. |
- 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