Jump to content

Issues with a file delete


bdg2814
 Share

Go to solution Solved by bdg2814,

Recommended Posts

I found a bit of code on one of the forum discussions that I thought I could use to clean backup files in two different directories.  I setup a loop that spins through an array that has a list of the file patterns to delete.

In the employee folder I have the following files

employee.csv

employee.csv.20131118201542

employee.csv.20131117201542

employee.csv.20131116201542

and in the custom folder I have the following files

customemp.csv

customemp.csv.20131118201542

customemp.csv.20131117201542

customemp.csv.20131116201542

The problem that I have is both the employee.csv file and the customemp.csv file are returned in the list of files to be tested for deletion.  I would think using the wildcard of 'name.csv.*' they would be eliminated from the list, but they are not.  I don't want to delete the employee.csv and the customemp.csv files but I do want to delete all of the other files with a date/time timestamp at the end of the file name that do meet the criteria. What am I missing?

Local $arr = ""
Local $search = ""
Local $file = ""
Local $CurrentDirectory = ""
Local $CurDir = ""

$File1 = "c:tempemplyeeemployee.csv.*"

$File2 = "c:tempcustomcustomemp.csv.*"
Local $DirList = $File1 & ',' & $File2
Local $TodaysDateIs = ""
Local $yyyymmdd = ""
Local $Loop = 0
Local $LoopMax = 0
Local $Cnt = 0

    $BackUpDays = 1

    $TodaysDateIs = (@YEAR & "/" & @MON & "/" & @MDAY) ; Sets up the date format for calculation, must use Year, month, day format

    $arr = StringSplit($DirList, ",")
    $LoopMax = $arr[0]

    For $Cnt = 1 to $LoopMax
        ; Shows the filenames of all files in the current directory, note that "." and ".." are returned.
        $CurDir = $arr[$Cnt]
        $search = FileFindFirstFile($CurDir)

        ; Check if the search was successful
        If $search = -1 Then
            Exit
        EndIf

        While 1
            $file = FileFindNextFile($search)
            If @error Then ExitLoop
            If $file = "." Then ContinueLoop ; Blocks output of the root directory "."
            If $file = ".." Then ContinueLoop ; Blocks output of the current directory ".."
            $FileDate = FileGetTime($file, 0, 0)
   
            If Not @error then
                $yyyymmdd = $FileDate[0] & "/" & $FileDate[1] & "/" & $FileDate[2]
           EndIf

            $DateDiffTotal = _DateDiff( 'D', $yyyymmdd,$TodaysDateIs)

            If $DateDiffTotal > $BackUpDays Then
               FileDelete($file) ; Actual delete statement.
            EndIf
        WEnd
    Next

    ; Close the search handle
    FileClose($search)

Link to comment
Share on other sites

Could you please be so kind and enclose your scripts in AutoIt code tags? That's the blue "A" icon in the editor.

That greatly enhances readability. Thanks :)

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Local $arr = ""
Local $search = ""
Local $file = ""
Local $CurrentDirectory = ""
Local $CurDir = ""

$File1 = "c:\temp\emplyee\employee.csv.*"

$File2 = "c:\temp\custom\customemp.csv.*"
Local $DirList = $File1 & ',' & $File2
Local $TodaysDateIs = ""
Local $yyyymmdd = ""
Local $Loop = 0
Local $LoopMax = 0
Local $Cnt = 0

    $BackUpDays = 1

    $TodaysDateIs = (@YEAR & "/" & @MON & "/" & @MDAY) ; Sets up the date format for calculation, must use Year, month, day format

    $arr = StringSplit($DirList, ",")
    $LoopMax = $arr[0]

    For $Cnt = 1 to $LoopMax
        ; Shows the filenames of all files in the current directory, note that "." and ".." are returned.
        $CurDir = $arr[$Cnt]
        $search = FileFindFirstFile($CurDir)

        ; Check if the search was successful
        If $search = -1 Then
            Exit
        EndIf

        While 1
            $file = FileFindNextFile($search)
            If @error Then ExitLoop
            If $file = "." Then ContinueLoop ; Blocks output of the root directory "."
            If $file = ".." Then ContinueLoop ; Blocks output of the current directory ".."
            $FileDate = FileGetTime($file, 0, 0)
   
            If Not @error then
                $yyyymmdd = $FileDate[0] & "/" & $FileDate[1] & "/" & $FileDate[2]
           EndIf

            $DateDiffTotal = _DateDiff( 'D', $yyyymmdd,$TodaysDateIs)

            If $DateDiffTotal > $BackUpDays Then
               FileDelete($file) ; Actual delete statement.
            EndIf
        WEnd
    Next

    ; Close the search handle
    FileClose($search)

Link to comment
Share on other sites

FileFindNextFile has not returned . or .. for several years as a choice was made to remove them being returned in AutoIt.

This code may help based on your pattern of use.

#include <date.au3>

_CsvCleanup('c:\temp\employee', 'employee.csv.*')
_CsvCleanup('c:\temp\custom', 'customemp.csv.*')

Func _CsvCleanup($working_dir = '.', $file_pattern = '*', $days_allowed = 1)
    Local $diff_date, $file_date, $file_found, $handle_find, $todays_date
    $handle_find = FileFindFirstFile($working_dir & '\' & $file_pattern)
    If $handle_find = -1 Then Return SetError(1, 0, 0)
    ; todays date as format yyyy/mm/dd
    $todays_date = @YEAR & "/" & @MON & "/" & @MDAY
    ;
    While 1
        $file_found = FileFindNextFile($handle_find)
        If @error Then ExitLoop
        If @extended Then ContinueLoop
        If Not StringRegExp($file_found, '\A.*\.\d{14}\Z') Then ContinueLoop
        ;
        $file_date = FileGetTime($working_dir & '\' & $file_found, 0, 1)
        If @error Then ContinueLoop
        $file_date = StringRegExpReplace($file_date, '(\d{4})(\d{2})(\d{2})\d{6}', '$1/$2/$3')
        If @extended <> 3 Then ContinueLoop
        ;
        $diff_date = _DateDiff( 'D', $file_date, $todays_date)
        If $diff_date > $days_allowed Then
            ConsoleWrite($diff_date & ' ' & $working_dir & '\' & $file_found & @CRLF)
;~          FileDelete($working_dir & '\' & $file_found)
        EndIf
    WEnd
    FileClose($handle_find)
EndFunc

The FileDelete is commented for testing reasons. The Regex pattern will check for 14 digits on the right side of the file name. Note that FileFindNextFile returns just a file name so it seems easier to add the code into a function and call it with each different path and to work with that path which can be prefixed to the file name. Changed FileGetTime to return a string so StringRegExpReplace can work with the 1st 8 digits of the string to set the date format yyyy/mm/dd and should be 3 replacements as the @extended test checks for.

:)

Link to comment
Share on other sites

  • Moderators

bdg2814, can you provide some examples of the backup files you do want to delete (.bak, .tmp?)? There should be a way to focus only on those, without having to exclude the employee and custemp files, unless I am missing something.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

In my first post I listed several examples of the file names.

in the employee folder I have the following files

employee.csv

employee.csv.20131118201542

employee.csv.20131117201542

employee.csv.20131116201542

and in the custom folder I have the following files

customemp.csv

customemp.csv.20131118201542

customemp.csv.20131117201542

customemp.csv.20131116201542

Link to comment
Share on other sites

  • Moderators

My apologies, I misread your original post and thought you wished to keep all those files. If employee.csv and customemp.csv are the only files you want to keep, you should be able to do so pretty easily with Melba's RecFileListToArray. I duplicated the folder structure in your OP, and this works for me and does not delete employee or customemp:

Edit: link to RecFileListToArray http://www.autoitscript.com/forum/index.php?showtopic=126198

#include <RecFileListToArray.au3>

Local $aArray = _RecFileListToArray(@DesktopDir & "\employee", "*", 1, 1, 1, 2, "employee.csv;customemp.csv")

If IsArray($aArray) Then
    For $i = 0 To $aArray[0]
        FileDelete($aArray[$i])
    Next
Else
    MsgBox(0, "", "No files found to delete.")
EndIf
Edited by JLogan3o13

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

  • Moderators

bdg2814,

Rather than putting the UDF into the standard include folder, I would recommend creating your own personal include folder as explained in the Adding UDFs to AutoIt and SciTE tutorial in the Wiki. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...