Sign in to follow this  
Followers 0
saurabh2k26

Rename all files in a folder in numerical order

13 posts in this topic

Hi

I have a folder "D:/test". It contains N number of jpeg files of same size and sorted alphabetically. I want them to rename. 

Rename 1st file as 1001.jpg, 2nd as 1002.jpg and so on.

Test Data:

2013-12-12.jpg

2013-12-15.jpg

2013-12-17.jpg

.......

Result Data:

1001.jpg

1002.jpg

1003.jpg

.......

Please give suggestion how to do this.

Share this post


Link to post
Share on other sites



use _FileListToArray() to read the files into array. by default it is sorted, but that may depend on the OS (Win2k for example does not sort), so use _ArraySort() on the array, then loop the array to rename each file in order.

Share this post


Link to post
Share on other sites

I am new to Autoit and can write simple code by referring syntax.

Can you help with code please.

Share this post


Link to post
Share on other sites

sure, let me just do a copy/paste from the AutoIt help file:

#include <File.au3>
#include <Array.au3>

Local $FileList = _FileListToArray(@DesktopDir)
If @error = 1 Then
    MsgBox(0, "", "No Folders Found.")
    Exit
EndIf
If @error = 4 Then
    MsgBox(0, "", "No Files Found.")
    Exit
EndIf
_ArrayDisplay($FileList, "$FileList")

this example will display a list of files & folders in your Desktop:

but let's start simple, ok? start by reading the help for _FileListToArray() (that reading would be less than a minute, really). then adapt the example to the target folder and file mask, and filter for files only.

i'm sure that when you get the concept of reading the help file and using the examples provided, you will need no further help to apply _ArraySort() and For loop on the array, and FileMove() to rename each file.

if by then you need any help, post whatever code you managed to write, and we will help you to get it running.

Share this post


Link to post
Share on other sites

sure, let me just do a copy/paste from the AutoIt help file:

In future just link to the help file, as the examples are likely to change over time. Case in point that example is old and incorrectly formatted.

e.g.

_FileListToArray() ; See the example by clicking on the link.

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Dear Orbs

I saw FileMove() function and i could not understand how to rename a file using it.

Test Data:

2013-12-12.jpg

2013-12-15.jpg

2013-12-17.jpg

.......

 

Result Data:

1001.jpg

1002.jpg

1003.jpg

.......

 

So, i need to use a variable VAR with initial value 1000. Find 1st file using _FileListArray and rename it as $VAR and then append $VAR by 1 in each loop and then remane 2nd file by new $VAR and so on.

 

Thanks

Share this post


Link to post
Share on other sites

To rename...

FileMove(@ScriptDir &'\OldFile.au3', @ScriptDir &'\NewFile.au3') ; v3.3.10.0 of AutoIt explains this.
If in doubt test it.

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Building on mikell's example...It might be better to fully qualify the file name and some error checking added...

local $path = 'k:\test\mikell\'     ;   change to your target path
local $ret
Local $hSearch = FileFindFirstFile($path & "*.jpg")
$i = 1
While 1
    $sFileName = FileFindNextFile($hSearch)
    If @error Then ExitLoop
    if FileMove($path & $sFileName, $path & String(1000+$i) & ".jpg", 0) = 1 then
        ConsoleWrite($path & $sFileName & ' renamed to ' & $path & String(1000+$i) & ".jpg" & @LF)
    Else
        ConsoleWrite('File rename failed for file = ' & $path & $sFileName & @LF)
    endif
    $i += 1
WEnd
FileClose($hSearch)

kylomas

1 person likes this

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Omitted error checking on $hSearch  :P


1 person likes this

Share this post


Link to post
Share on other sites

Why not use _FileListToArray()? It's easier and less complicated for the user to understand.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Saurabh2k26,

You could also do it this way.

#include <File.au3>
Opt("MustDeclareVars", 1)

Global $sPathToFiles = "D:\test\"
Global $newFileName = 1000
Global $aFilesToRename = ""

;Get file names to rename
$aFilesToRename = _FileListToArray($sPathToFiles, "*.jpg", 1)

;Loop through file names to Rename
For $i = 1 To $aFilesToRename[0]

    ;increment new file name by 1 with each pass of loop. 1001.jpg, 1002.jpg etc
    $newFileName += 1

    ;Rename files
    FileMove($sPathToFiles & $aFilesToRename[$i], $sPathToFiles & String($newFileName) & ".jpg", 0)

Next

-

This version is a little bit more involved but not by much - here is the script with some error checking and user prompting.

#include <GUIConstantsEx.au3>
#include <File.au3>
#include <Array.au3>

Opt("MustDeclareVars", 1)

Global $sPathToFiles = "D:\test\"
Global $newFileName = 1000
Global $aFilesToRename = ""


_Main()



Func _Main()
    _GetFileNamesToRename()

    _ArrayDisplay($aFilesToRename) ;Show me found files

    _RenameTheFiles()
EndFunc ;==> _Main()



Func _GetFileNamesToRename()
    $aFilesToRename = _FileListToArray($sPathToFiles, "*.jpg", 1)

    ;Check if _FileListToArray() returned an error
    If $aFilesToRename = 0 Then
        Select
            Case @error = 1
                Msgbox(48, "Error", "Path not found or invalid." & @CRLF & "Terminating script")
                Exit
            Case @error = 2
                Msgbox(48, "Error", "Invalid file filter. [$sFilter]." & @CRLF & "Terminating script")
                Exit
            Case @error = 3
                Msgbox(48, "Error", "Invalid Flag. [$iFlag]" & @CRLF & "Terminating script")
                Exit
            Case @error = 4
                Msgbox(48, "Error", "No File(s) Found" & @CRLF & "Terminating script")
                Exit
        EndSelect
    EndIf
EndFunc ;==> _GetFileNamesToRename()



Func _RenameTheFiles()
    Local $iMsgboxReturn

    ;Alert user files are about to be renamed / Ask user for confirmation via buttons
    $iMsgboxReturn = Msgbox(64+1, "Confirm Rename", $aFilesToRename[0] & chr(32) _
                & "File(s) in this directory:" & @CRLF & $sPathToFiles & chr(32) _
                & @CRLF & "will be renamed.")

    ;Check confirmation (1 = ok btn, 2 = cancel btn)
    If $iMsgboxReturn = 2 Then
        Msgbox(16, "File Rename cancelled", "File Rename canceled." & @CRLF & "Click OK to terminate file rename.")
        Exit
    EndIf

    ;Loop through file names to Rename
    For $i = 1 To $aFilesToRename[0]

        ;increment new file name by 1 with each pass of loop
        $newFileName += 1

        ;Rename files
        FileMove($sPathToFiles & $aFilesToRename[$i], $sPathToFiles & String($newFileName) & ".jpg", 0)

        ;Alert user files have been renamed
        If $i = $aFilesToRename[0] Then
            MsgBox(64, "Files Renamed", $i & chr(32) & "Files have been renamed.")
            Exit
        EndIf
    Next
EndFunc ;==> _RenameTheFiles()
1 person likes this

Share this post


Link to post
Share on other sites

Hi kylomas

Your solution work for me.

Thanks a lot.

:)

Share this post


Link to post
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
Sign in to follow this  
Followers 0