Jump to content

Newb needs help recursing so he will stop cursing.


EBJoe
 Share

Recommended Posts

I have a script (complete script below) that does a fine job of doing what I want it to do I.E. read the directory it's in and make an m3u file of all mp3's in that directory, named directory name.

Global $filetype = "mp3"
Global $i = 0
Global $file = 0
Global $temp[500]
Global $saveas

$temp = StringSplit(@ScriptDir, "\")
$saveas = "" & $temp[$temp[0]] & ".m3u"
$search = FileFindFirstFile("*." & $filetype)

If $search = -1 Then
    MsgBox(0, "Error", "No files/directories matched the search pattern")
    Exit
EndIf

While 1
    $file = FileFindNextFile($search) 
    If @error Then ExitLoop
    
    FileWriteLine($saveas, $file)
WEnd

FileClose($search)

Is there a way to use recursing of some sort ($iRecurse or something) so it will make m3u files like this...

directory 1 (5 mp3's)

subdirectory A (11 mp3's)

subdirectory B (1 googleplex mp3's)

etc...

Basically, what I'm looking for is to be able to run the script in directory 1 and have it make m3u files in directory 1 and all directories below it, with the mp3's in that particular directory in that directory's m3u file.

Link to comment
Share on other sites

  • Moderators

BJoe,

If you search for "+recursive +file +search" you will find no end of example scripts (including some of mine) showing you how to search through subfolders. ;)

They tend to be of 2 types:

- Full recursion: The internal function keeps calling itself.

- List recursion: New folders are added to a list and dealt with in turn.

Personally I prefer the latter - I try to avoid full recursion like the plague if I possibly can. ;)

Come back if you cannot find a suitable script (which I doubt) or you have problems integrating one of the ones you do find into your code. :)

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

One way cuz I'm tipsy

#include<Array.au3>

$TopDirectory = FileSelectFolder('Select Top-Level Folder', '', _GetIEVersion(), '')
If @error Then Exit
Local $FolderArray = _FileListToArray_Recursive($TopDirectory, '*', 2, 2, True)
If Not IsArray($FolderArray) Then Local $FolderArray[2] = [1, $TopDirectory]

_ArrayDisplay($FolderArray, 'Directories To Search')

For $i = 1 To $FolderArray[0]
    _Splash('Checking Folder: ' & StringRegExpReplace($FolderArray[$i], '^.+\\', '') & ' #' & $i & ' of ' & $FolderArray[0])
    Sleep(500)
    _MakeM3U($FolderArray[$i])
Next

;===============================================================================
Func _MakeM3U($InDirectory)
    Local $i, $String, $FileName, $Output
    If Not FileExists($InDirectory) Then Return MsgBox(32, ' Directory ERROR', $InDirectory & ' does not exists')
    FileChangeDir($InDirectory)
    $FileName = StringRegExpReplace($InDirectory, '^.+\\', '') & '.m3u'
    Local $MP3Array = _FileListToArray_Recursive($InDirectory, '*.mp3', 1, 0)
    If Not IsArray($MP3Array) Then
        _Splash('No MP3 Files Found in ' & $InDirectory)
        Sleep(500)
        Return
    EndIf
    For $i = 1 To $MP3Array[0]
        $String &= $MP3Array[$i]
        If $i <> $MP3Array[0] Then $String &= @CRLF
    Next
    If FileExists($FileName) Then FileMove($FileName, StringTrimRight($FileName, 4) & '-old.m3u')
    $Output = FileOpen($FileName, 2)
    FileWrite($Output, $String)
    FileClose($Output)
EndFunc   ;==>_MakeM3U

;===============================================================================
; $iRetItemType: 0 = Files and folders, 1 = Files only, 2 = Folders only
; $iRetPathType: 0 = Filename only, 1 = Path relative to $sPath, 2 = Full path/filename
Func _FileListToArray_Recursive($sPath, $sFilter = "*", $iRetItemType = 0, $iRetPathType = 0, $bRecursive = False)
    Local $sRet = "", $sRetPath = ""
    $sPath = StringRegExpReplace($sPath, "[\\/]+\z", "")
    If Not FileExists($sPath) Then Return SetError(1, 1, "")
    If StringRegExp($sFilter, "[\\/ :> <\|]|(?s)\A\s*\z") Then Return SetError(2, 2, "")
    $sPath &= "\|"
    $sOrigPathLen = StringLen($sPath) - 1
    While $sPath
        $sCurrPathLen = StringInStr($sPath, "|") - 1
        $sCurrPath = StringLeft($sPath, $sCurrPathLen)
        $Search = FileFindFirstFile($sCurrPath & $sFilter)
        If @error Then
            $sPath = StringTrimLeft($sPath, $sCurrPathLen + 1)
            ContinueLoop
        EndIf
        Switch $iRetPathType
            Case 1 ; relative path
                $sRetPath = StringTrimLeft($sCurrPath, $sOrigPathLen)
            Case 2 ; full path
                $sRetPath = $sCurrPath
        EndSwitch
        While 1
            $File = FileFindNextFile($Search)
            If @error Then ExitLoop
            If ($iRetItemType + @extended = 2) Then ContinueLoop
            $sRet &= $sRetPath & $File & "|"
        WEnd
        FileClose($Search)
        If $bRecursive Then
            $hSearch = FileFindFirstFile($sCurrPath & "*")
            While 1
                $File = FileFindNextFile($hSearch)
                If @error Then ExitLoop
                If @extended Then $sPath &= $sCurrPath & $File & "\|"
            WEnd
            FileClose($hSearch)
        EndIf
        $sPath = StringTrimLeft($sPath, $sCurrPathLen + 1)
    WEnd
    If Not $sRet Then Return SetError(4, 4, "")
    Return StringSplit(StringTrimRight($sRet, 1), "|")
EndFunc   ;==>_FileListToArray_Recursive

;===============================================================================
Func _Splash($Text) ;Shows a small borderless splash message.
    SplashTextOn('', $Text, @DesktopWidth, 25, -1, 5, 33, '', 14)
EndFunc   ;==>_Splash

;===============================================================================
Func _GetIEVersion()
    Select
        Case FileExists(@ProgramFilesDir & '\Internet Explorer\iexplore.exe')
            $iE_Version = FileGetVersion(@ProgramFilesDir & '\Internet Explorer\iexplore.exe')
        Case @OSArch = 'X64'
            If FileExists(StringRegExpReplace(@ProgramFilesDir, '(?i) \(x86\)', '') & '\Internet Explorer\iexplore.exe') Then $iE_Version = FileGetVersion(StringRegExpReplace(@ProgramFilesDir, '(?i) \(x86\)', '') & '\Internet Explorer\iexplore.exe')
        Case Else
            Return 4
    EndSelect
    Switch Int($iE_Version)
        Case 0 To 4
            Return 4
        Case 5
            Return 2 + 4
        Case Else
            Return 1 + 2 + 4
    EndSwitch
EndFunc   ;==>_GetIEVersion

Link to comment
Share on other sites

f&#(.

Can somebody check my work?

global $m3ucount,$mp3count

$basedir=@WorkingDir

$action="del"
theheart($basedir)

$action="m3u"
theheart($basedir)

;$action="html"
;FileDelete($basedir&"\masmo.html")
;$html=FileOpen($basedir&"\masmo.html",1)
;FileWriteLine($html,"<body bgcolor=""black"" link=""14ff00"">"&@CRLF)
;theheart($basedir)
;FileClose($html)

;$action="count"
;theheart($basedir)

;msgbox(0,"M3Us Created:",$m3ucount)
;msgbox(0,"MP3s Found:",$mp3count)


func theheart($basedir)
    
    $basesearch = fileFindFirstFile($basedir & "\*.*")
    if $basesearch==-1 then return 0 ; specified folder is empty!
    while @error<>1
        $basefile = fileFindNextFile($basesearch)
        ; skip these
        if $basefile=="." or $basefile==".." or $basefile=="" then
            continueLoop
        endIf
        ; if it's a dir then call this function again (nesting the function is clever ;)
        if stringInStr(fileGetAttrib($basedir & "\" & $basefile), "D") > 0 then
            if $action="del" then 
                FileDelete($basedir&"\"&$basefile&"\*.m3u")
            EndIf
            if $action="count" then 
                $m3ucount+=1
            EndIf
            if $action="html" then 
                $formattedfile=""""&$basedir&"\"&$basefile&""""
                $trim=StringRight($formattedfile,(stringlen($formattedfile)-8))
                $slashpos=StringInStr($trim,"\")
                $folder=StringLeft($trim,$slashpos-1)
                FileWriteLine($html,"<br><br><center><font size=""+3""><a href="""&$basedir&"\"&$basefile&"\"&$basefile&".m3u"""&">"&$basefile&"</a></center></font><br>")
            EndIf
            theheart($basedir & "\" & $basefile)
        else
            ; Files we need to deal with
            if $action="m3u" Then
                $extension=StringLower(Stringright($basefile,4))
                if $extension=".mp3" or $extension=".wma" Then
                    $mp3count+=1
                    $formattedfile=""""&$basedir&"\"&$basefile&""""
                    $trim=StringRight($formattedfile,(stringlen($formattedfile)-8))
                    $slashpos=StringInStr($trim,"\")
                    $folder=StringLeft($trim,$slashpos-1)
                    $m3u=fileopen($basedir&"\"&$folder&".m3u",1)
                    FileWriteLine($m3u,$basefile)
                    fileclose($m3u)
                EndIf
            EndIf
            if $action="html" Then
                $ext=StringRight($basefile,4)
                FileWriteLine($html,"<a href="""&$basedir&"\"&$basefile&""">"&StringTrimRight($basefile,4)&"</a><br>")
            EndIf
        EndIf
    wEnd
fileClose($basesearch)
return 1
endFunc

I got this almost where I want it. The only problem is all I get is "y Music.m3u" in my directories. Can somebody tell me how to get it to write *FOLDERNAME.M3U*?

I've been trying everything I know (which ain't much) for an hour with no luck.

Link to comment
Share on other sites

One quick note, if you are going to use variables both outside and inside a function (and as a general rule for debugging), you should declare then with "Global" or "Local" if they only need to exist inside a function or outside in the main script. Other than that, it grabs all the files in the working directory, not just the mp3 files. I am having trouble following the flow of your script. FYI, I applaud your desire to make your own script. That will serve you well in future endeavors

Edited by Varian
Link to comment
Share on other sites

Thanks for the help. Unfortunately, as I learned a year ago when I put the script down, AutoIt just isn't a good enough program to make a script do what I want it to do (AND I'm too damn lazy to learn c++). Oh well. I'll check back in another year and see if the program's been upgraded enough to make a script to do what I want it to do.

Link to comment
Share on other sites

Thanks for the help. Unfortunately, as I learned a year ago when I put the script down, AutoIt just isn't a good enough program to make a script do what I want it to do (AND I'm too damn lazy to learn c++). Oh well. I'll check back in another year and see if the program's been upgraded enough to make a script to do what I want it to do.

It can do most things, you just don't know how to make it do what you want it to... ;)
Link to comment
Share on other sites

I wish it were that easy. If that were the case, I could learn how to make it do A + B = C. But you are right, it can do MOST things, it just can't get A + B to equal C, I have to make 2 scripts, A and B. Not that that's a terrible thing, it would just be nice to get C out of one.

Link to comment
Share on other sites

@varian

Thanks for your _GetIEVersion() Function !

I was looking for a long time Posted Image

No problem...I only use it with "FileSelectFolder"

Thanks for the help. Unfortunately, as I learned a year ago when I put the script down, AutoIt just isn't a good enough program to make a script do what I want it to do (AND I'm too damn lazy to learn c++). Oh well. I'll check back in another year and see if the program's been upgraded enough to make a script to do what I want it to do.

Have you tested my script?? It does EXACTLY what you want! AutoIT cannot do many things, but for this task, it's a breeze. Don't give up on trolling the Forum for snippets and examples for your solutions to problems.
Link to comment
Share on other sites

Can you tell me what about it is not working? Is it failing with an error out or is it not creating the m3u files? I only made it create a basic m3u file (a text list), but if you say how it is failing for you, perhaps I can help. Is your Include path in the AutoIT registry? Can you run au3check.exe and see if it gives you any errors?

Hey wakillon, can you test the script to see if you have any errors/issues with it?

Link to comment
Share on other sites

  • Moderators

Varian,

Just tested and working perfectly for me (Vista HP x32 SP2).

Nice script. ;)

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

Varian,

Just tested and working perfectly for me (Vista HP x32 SP2).

Nice script. ;)

M23

Thanks for that! I knew I wasn't crazy! This script was too simple for me to have goofed up! I build/test my scripts on 2k8R2(only 64-bit) before I post to make sure I don't put out buggies
Link to comment
Share on other sites

Can you tell me what about it is not working? Is it failing with an error out or is it not creating the m3u files? I only made it create a basic m3u file (a text list), but if you say how it is failing for you, perhaps I can help. Is your Include path in the AutoIT registry? Can you run au3check.exe and see if it gives you any errors?

Hey wakillon, can you test the script to see if you have any errors/issues with it?

Works fine for me too ! Posted Image

AutoIt 3.3.14.2 X86 - SciTE 3.6.0WIN 8.1 X64 - Other Example Scripts

Link to comment
Share on other sites

  • Moderators

EBJoe,

If you look at Varian's script above, you will find line 32 reads:

If FileExists($FileName) Then FileMove($FileName, StringTrimRight($FileName, 4) & '-old.m3u')

Just delete or comment out that line. The line following it overwrites and destroys any existing file - because the FileOpen uses the "2 = Write mode (erase previous contents)" flag. So there is nothing there to delete! ;)

Personally I prefer Varian's decision to rename rather then delete, but that is your choice. :)

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

I tried that. It will overwrite directoryname.m3u, but a lot (Maybe 99%) of the time, I have m3u's that are different than the directory name, so they don't get overwritten.

I need a line to delete ANY m3u that's there before the new one gets written.

Link to comment
Share on other sites

uuuuuuuuhhhhhhhhh nevermind. :) slash. And maybe, just maybe, I can stop ;) .

I feel like I've ;) from scripting kindergarten. I think I will go eat lunch at :shocked: . And now, I will stop this post, since I've used more emoticons on it than I have in the last decade combined (Yeah, I'm old, no, I do NOT like it).

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...