Home > Mobile >  Python For loop not iterating through directories
Python For loop not iterating through directories

Time:04-02

Am trying to delete the files between two dates in a folder contains several sub folders. I want to keep the latest the 14 days files and to delete the remaining 16 files in a month in all subfolders. My current script is deleting first directory D:\S135\firstdirectory and going to else block without touching remaining folders.

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

The code

import os
import time
import datetime

def main():
    start_date = datetime.datetime.strptime('2022-03-01', '%Y-%m-%d')
    to_delete = 'D:\S135'

    if os.path.exists(to_delete):
        if os.path.isdir(to_delete):
            for root_folder, folders, files in os.walk(to_delete):
                for file in files:
                    curpath = os.path.join(to_delete, file)
                    file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
                    if datetime.datetime.now() - file_modified > datetime.timedelta(days=14):   
                        if file_modified > start_date :
                            print(curpath)

if __name__ == "__main__":
    # invoking main function
    main()

CodePudding user response:

Change

                    curpath = os.path.join(to_delete, file)

to

                    curpath = os.path.join(root_folder, file)

because the names in files are relative to the current directory of the recursion, not the folder that you started from.

CodePudding user response:

Try to add topdown=true

for root_folder, folders, files in os.walk(to_delete, topdown=true)
  • Related