Removing files from folders in Python

I am removing a certain file from many folders. But when that file is missing in a folder, it runs into an error. Basically, I want the code to scan every folder, see if the file exists there and delete it. If there is no file in a specific folder, it should skip that since there is nothing to delete and move to the next folder.

import os
N = [i+1 for i in range(101)]
I=[]

for i in N:
    if i in I:
        continue
    os.remove(rf"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3\{i}\Indices.txt")

The error is

FileNotFoundError: [WinError 2] The system cannot find the file specified.

>Solution :

Python has something called try / except allowing you to perform an action that could raise an exception, catch this exception if it is raised, and act consequently.

I simply added it to your code for you to see an example: the script now tries to remove the file. If it cannot do it because the file does not exist, then it will raise a FileNotFoundError that will be catched by the except block, where it prints something.

import os
import sys
N = [i+1 for i in range(101)]
I=[]

for i in N:
    if i in I:
        continue
    try:
        os.remove(rf"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3\{i}\Indices.txt")
    except FileNotFoundError:
        print("File does not exist", file=sys.stderr)

Leave a Reply