Monday, April 21, 2025

Delete File - os.remove() Example

import os

files = ['new-1.txt', 'new-2.txt', 'new-3.txt']

for x in files:
    os.remove(x)

This Python code imports the "os" module using the "import" statement.

Then, the code initializes a list variable named "files" with three string values: 'new-1.txt', 'new-2.txt', and 'new-3.txt'.

The code then enters a "for" loop that iterates over each element (a string value) of the "files" list. In each iteration of the loop, the code calls the "os.remove()" function to delete the file with the corresponding file name from the current working directory. The name of the file to be deleted is passed as an argument to the "os.remove()" function.

So, when the program is executed, the files with the names 'new-1.txt', 'new-2.txt', and 'new-3.txt' will be deleted from the current working directory. If the files do not exist in the directory, the "os.remove()" function will raise a "FileNotFoundError".

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...