Jump to content

Looping through files


Recommended Posts

Hi all, Pretty new to AutoIt,

I am stuck writing a script and hopefully someone can help me figure out an outcome.

the script is supposed to loop trough a file and store the value of one whole line into a variable

then it needs to loop through a folder and find an image file that matches the variable name

if a match is found it then save the image file as the first 9 digits of the line

now it also has to delete the leading zeros if there are ones in the first line

Here is the code I have so far, I did two functions, one that gets the line and another that gets the image file name

but cannot get the looping part. I hope anyone can direct me to its solution and thanks in advance.

$TextFileName =  @ScriptDir & "\CEREIndex.txt"; 

$ImgFileName = @scriptdir & "\CERESOFT-P"
$CompareFile = ""
$TrimedString = ""

main()

Func main()
$img = ""
$var = ""
;msgbox(0," Pt No is ", "" & ReadTextFile($var))
;

Do
    msgbox(0," File is", "" & FindImg($img))
    Until @error

EndFunc

func FindImg(ByRef $img)
    
    $ImgPath = @scriptdir & "\CERESOFT-P\" 
    $ImgSearch = FileFindFirstFile ($ImgPath  & "*.*")
    
    while 1
        $file = FileFindNextFile($imgsearch)
        if $file = "" Then
            exit
            else
        
        $comparefile = $File
    endif
;MsgBox(0," File" , "The file is: " & $CompareFile)
    $img = $CompareFile
    Return $img 
;ExitLoop
WEnd

EndFunc




Func ReadTextFile(ByRef $var)

    $file = FileOpen(@ScriptDir & "\CEREIndex.txt", 0)

If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
   $line = FileReadLine($file)
        If @error = -1 Then 
          MsgBox(0, "Error", "End of file.", 1)
    Exit
endif

$TrimedString = stringleft($line, 1)
$var = ""
$x = 0
Do
    $x = $x + 1
    $var = StringMid($line, $x, 9)
Until StringLeft($var,1) > 0
Return  $var
WEnd

FileClose($file)
endfunc

Just another special date with a different challenge

Link to comment
Share on other sites

I would start by using a For...In...Next loop instead of the While 1 \ Do loops you are using now.

For example

For $img In FileReadLine($file)
 Do your comparison
Next
That won't work and the syntax is completely wrong. Please try out your answers before you post.

:)

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

Hi all, Pretty new to AutoIt,

I am stuck writing a script and hopefully someone can help me figure out an outcome.

the script is supposed to loop trough a file and store the value of one whole line into a variable

then it needs to loop through a folder and find an image file that matches the variable name

if a match is found it then save the image file as the first 9 digits of the line

now it also has to delete the leading zeros if there are ones in the first line

Here is the code I have so far, I did two functions, one that gets the line and another that gets the image file name

but cannot get the looping part. I hope anyone can direct me to its solution and thanks in advance.

CODE
$TextFileName = @ScriptDir & "\CEREIndex.txt";

$ImgFileName = @scriptdir & "\CERESOFT-P"

$CompareFile = ""

$TrimedString = ""

main()

Func main()

$img = ""

$var = ""

;msgbox(0," Pt No is ", "" & ReadTextFile($var))

;

Do

msgbox(0," File is", "" & FindImg($img))

Until @error

EndFunc

func FindImg(ByRef $img)

$ImgPath = @scriptdir & "\CERESOFT-P\"

$ImgSearch = FileFindFirstFile ($ImgPath & "*.*")

while 1

$file = FileFindNextFile($imgsearch)

if $file = "" Then

exit

else

$comparefile = $File

endif

;MsgBox(0," File" , "The file is: " & $CompareFile)

$img = $CompareFile

Return $img

;ExitLoop

WEnd

EndFunc

Func ReadTextFile(ByRef $var)

$file = FileOpen(@ScriptDir & "\CEREIndex.txt", 0)

If $file = -1 Then

MsgBox(0, "Error", "Unable to open file.")

Exit

EndIf

While 1

$line = FileReadLine($file)

If @error = -1 Then

MsgBox(0, "Error", "End of file.", 1)

Exit

endif

$TrimedString = stringleft($line, 1)

$var = ""

$x = 0

Do

$x = $x + 1

$var = StringMid($line, $x, 9)

Until StringLeft($var,1) > 0

Return $var

WEnd

FileClose($file)

endfunc

That's a confused script. Start small with the first function and make that work. Then add to it one piece at a time.

The first step you describe is read each line in a file. The function ReadTextFile() you have does that, but what you are doing with the line makes no sense. I can't see how you tested that and got any output at all. Try this:

$TextFileName = @ScriptDir & "\CEREIndex.txt"

ReadTextFile()

Func ReadTextFile()
    Local $sLine, $hFile
    
    $hFile = FileOpen($TextFileName, 0)
    If $hFile = -1 Then
        MsgBox(16, "Error", "Unable to open file.")
        Exit
    EndIf

    While 1
        $sLine = FileReadLine($hFile)
        If @error = -1 Then
            MsgBox(16, "Error", "End of file.", 1)
            ExitLoop
        EndIf
        ConsoleWrite("$sLine = " & $sLine & @LF)
    WEnd

    FileClose($hFile)
EndFunc  ;==>ReadTextFile

:)

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

Or maybe this for your 'FileReadText' function,

Source :

#Include <File.Au3>
$iFile = @ScriptDir & '\CEREIndex.txt'

_ReadTextFile ()

Func _ReadTextFile ()
Local $iLine, $iOpen
$iOpen = FileOpen ($iFile, '0')
If $iOpen = '-1' Then 
Exit MsgBox ('16','Error','Cannot open file.','0')
EndIf 
For $A = '1' To _FileCountLines ($iFile)
$iLine = FileReadLine ($iOpen, $A)
ConsoleWrite ('Line : ' & $A & ', Value : ' & $iLine & @CRLF)
Next
FileClose ($iOpen)
EndFunc

Hope it helps! :)

- John

Edit : Are you trying to read each line of a text file and if the value of the current file matches the name of a image file then copy the image file to a new location and name it the first 9 letters of the 'search-string'? If so then I can make you a decent example.

Edited by John2006

Latest Projects :- New & Improved TCP Chat

Link to comment
Share on other sites

Any other hint or sample code. Still stuck.

what I need to do is match the picture file names with the lines on a text file (please see illustration)

when i find a match i then save the picture file as the first 9 digits (excluding leading zeros)

If anyone can just point me some where I will appreciate it. I tried the examples above but not luck. Im pretty new programming.

Thanks again

Just another special date with a different challenge

Link to comment
Share on other sites

So after some trys.. I think I got it for ya!

Source :

#Include <File.Au3>
#Include <String.Au3>

$Search_File = @ScriptDir & '\CEREIndex.txt'; This is the text file with the 'search-values'.
$Scan_Folder = @ScriptDir & '\CERESOFT-P'; This is the folder/path with the images.
$Result_Folder = 'Result'; This is where the images that match the value(s) of the text file will be copied to.
If DirGetSize ($Result_Folder) = '-1' Then DirCreate ($Result_Folder); If the result folder is not there then create it.
$Count = _FileCountLines ($Search_File)
$List = _FileListToArray ($Scan_Folder, '*','1')

For $A = '1' To $Count
$Read = FileReadLine ($Search_File, $A)
$List = _FileListToArray ($Scan_Folder, '*','1')
For $B = '1' To $List['0']
$Current = $Scan_Folder & '\' & $List[$B]
If StringInStr (_FileGetName ($List[$B]), $Read) <> '0' Then 
$New = $Result_Folder & '\' & StringLeft ($Read, '9') & _FileGetType ($List[$B])
If FileExists ($New) Then 
$New = $Result_Folder & '\' & $List[$B]; Makes sure all fils will correctly be copied.
EndIf 
$Copy = FileCopy ($Current, $New, '1')
EndIf 
Next
Next

Func _FileGetName ($iFile)
$Char = StringSplit (_FileGetType ($iFile), '')
$Char = $Char['0']
Return StringTrimRight ($iFile, $Char)
EndFunc

Func _FileGetType ($iFile)
$String = _StringReverse ($iFile)
$String = StringSplit ($String, '.')
$String = '.' & _StringReverse ($String['1'])
Return $String
EndFunc

Hope it helps! :)

- John

Also if you have any questions then feel free to ask!

Edited by John2006

Latest Projects :- New & Improved TCP Chat

Link to comment
Share on other sites

Thanks John, I tried the code, but only create the Result folder but no image files and no errors.

I am checking to see if I can handle it from here, but will appreciate if can provide more input.

thanks again

Just another special date with a different challenge

Link to comment
Share on other sites

Thanks John, I tried the code, but only create the Result folder but no image files and no errors.

I am checking to see if I can handle it from here, but will appreciate if can provide more input.

thanks again

hi,

Could you maybe post an example of the CEREIndex.txt in your 1st post?

Edited by smashly
Link to comment
Share on other sites

Hi

I had a play with it and this was what I came up with

Global $TxtFile = @ScriptDir & "\CEREIndex.txt"
Global $ImagePath = @ScriptDir & "\CERESOFT-P"
Global $aImg, $aTxt

$aImg = _ImageNameToArray($ImagePath)
$aTxt = _TextToArray($TxtFile)

For $i = 1 To $aTxt[0]
    For $j = 1 To Ubound($aImg) -1
        If StringStripWS($aTxt[$i], 3) = $aImg[$j] Then _
        FileCopy($aImg[0] & $aImg[$j], $aImg[0] & "Renamed\" & _Rename($aImg[$j]), 8)
    Next
Next

Func _Rename($sName)
    Local $sRet = $sName, $sExt = StringMid($sRet, StringInStr($sRet, ".", 0, -1))
    While (StringLeft($sRet, 1) = "0" And StringLen($sRet) > (9 + StringLen($sExt)))
        $sRet = StringTrimLeft($sRet, 1)
    WEnd
    $sRet = StringLeft($sRet, 9) & $sExt
    Return $sRet
EndFunc 

Func _ImageNameToArray($sPath, $sTypes = "bmp|gif|ico|jpg|jpe|jpeg|jfif|png|tif|tiff")
    Local $IP = $sPath, $aExt, $First, $Next, $sTmp, $i = 0
    If StringRight($sPath, 1) <> "\" Then $IP &= "\"
    $sTmp = $IP & "|"
    $First = FileFindFirstFile($IP & "*")
    If $First = -1 Then
        MsgBox(0, "Error", "No files matched the image search pattern")
        Exit
    EndIf
    While 1 
        $Next = FileFindNextFile($First) 
        If @error Then ExitLoop
        If StringRegExp($Next, "(?i)\.(" & $sTypes & ")", 0) Then $sTmp &= $Next & "|"
    WEnd
    Return StringSplit(StringTrimRight($sTmp, 1), "|", 2)
EndFunc 
    
Func _TextToArray($sPath)
    Local $FO, $FR
    $FO = FileOpen($sPath, 0)
    If $FO = -1 Then
        MsgBox(0, "Error", "Unable to open: " & $sPath)
        Exit
    EndIf
    $FR = FileRead($FO)
    FileClose($FO)
    Return StringSplit(StringStripWS(StringStripCR($FR), 7), @LF)
EndFunc
There's barely any error checking, so maybe use it on a dummy archive.

The script copies the renamed file matches into a directory called "Renamed" in the image directory.

Edit: mild code change to allow for if a image name is less then 9 characters + .ext len then stop stripping leading 0's

Also remove leading/trailing white spaces from the text when comparing it to the image name.

Edit again:

changed my method of File extension of an image can be more then 3 char eg; tiff or jpeg

So the extension length is now formulated and not hard set

Edited by smashly
Link to comment
Share on other sites

Hi all, Thanks for the replies. John/smashly I appreciate your help with the code.

I used the codes from John and this is what I got the results I needed. However, I changed the string replace function because I wanted only to eliminate the Leading zeros from the result. So in this case I knew that there where instances of 3 zeros but that may not be always the case.

If someone, can give me a hint I'll appreciate it.

Thanks again everyone for the input

#Include <File.Au3>
#Include <String.Au3>
$iScanFile = @ScriptDir & '\CEREIndex.txt'
$iScanFolder = @ScriptDir & '\CERESOFT-P'
$iResultFolder = @ScriptDir & '\Result'
If DirGetSize ($iResultFolder) = '-1' Then DirCreate ($iResultFolder)
For $A = '1' To _FileCountLines ($iScanFile)
$Split = FileReadLine ($iScanFile, $A)
$Split = StringSplit ($Split, '|')
$Name = _GetCorrectName ($Split['1'])
$Type = _FileGetType ($Split['4'])
$New = $iResultFolder & '\' & $Name & $Type
$File = $iScanFolder & '\' & $Split['4']
FileCopy ($File, $New, '1')
Next


Func _GetCorrectName ($iData)
$iString = ('A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z')


$ireturn = $iData

;$iReturn =StringReplace ($iData, '0','' )

$iString = StringSplit ($iString, '|')

For $iA = '1' To $iString['0']

if StringLeft($ireturn, 3) = 0 Then
    $ireturn = StringTrimLeft ($ireturn, 3 )
    endif

;$iReturn = StringReplace ($iReturn, $iString[$iA], '')
;  $iReturn = $iData

Next
Return StringLeft ($iReturn, '9')
Return $iReturn
EndFunc


Func _FileGetType ($iFile)
$String = _StringReverse ($iFile)
$String = StringSplit ($String, '.')
$String = '.' & _StringReverse ($String['1'])
Return $String
EndFunc

Just another special date with a different challenge

Link to comment
Share on other sites

Hi all, Thanks for the replies. John/smashly I appreciate your help with the code.

I used the codes from John and this is what I got the results I needed. However, I changed the string replace function because I wanted only to eliminate the Leading zeros from the result. So in this case I knew that there where instances of 3 zeros but that may not be always the case.

If someone, can give me a hint I'll appreciate it.

Thanks again everyone for the input

#Include <File.Au3>
#Include <String.Au3>
$iScanFile = @ScriptDir & '\CEREIndex.txt'
$iScanFolder = @ScriptDir & '\CERESOFT-P'
$iResultFolder = @ScriptDir & '\Result'
If DirGetSize ($iResultFolder) = '-1' Then DirCreate ($iResultFolder)
For $A = '1' To _FileCountLines ($iScanFile)
$Split = FileReadLine ($iScanFile, $A)
$Split = StringSplit ($Split, '|')
$Name = _GetCorrectName ($Split['1'])
$Type = _FileGetType ($Split['4'])
$New = $iResultFolder & '\' & $Name & $Type
$File = $iScanFolder & '\' & $Split['4']
FileCopy ($File, $New, '1')
Next


Func _GetCorrectName ($iData)
$iString = ('A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z')


$ireturn = $iData

;$iReturn =StringReplace ($iData, '0','' )

$iString = StringSplit ($iString, '|')

For $iA = '1' To $iString['0']

if StringLeft($ireturn, 3) = 0 Then
    $ireturn = StringTrimLeft ($ireturn, 3 )
    endif

;$iReturn = StringReplace ($iReturn, $iString[$iA], '')
;  $iReturn = $iData

Next
Return StringLeft ($iReturn, '9')
Return $iReturn
EndFunc


Func _FileGetType ($iFile)
$String = _StringReverse ($iFile)
$String = StringSplit ($String, '.')
$String = '.' & _StringReverse ($String['1'])
Return $String
EndFunc
hi,

I already supplied the function to strip the leading 0's

Func _Rename($sName)
    Local $sRet = $sName, $sExt = StringMid($sRet, StringInStr($sRet, ".", 0, -1))
    While (StringLeft($sRet, 1) = "0" And StringLen($sRet) > (9 + StringLen($sExt)))
        $sRet = StringTrimLeft($sRet, 1)
    WEnd
    $sRet = StringLeft($sRet, 9) & $sExt
    Return $sRet
EndFunc

Feed the funtion a file string and it returns the the string minus the leading 0' s...

The function will return the string as 9 characters long + .ext

The only time it won't strip the laeding 0's is if the total file name is 9 + .extenson length characters or less as you said only want the first 9 characters after any leading 0's for the file name.

I'd suggest you grab the attachment I posted and try out what I wrote, it could maybe help you..

Edit: changed the way an extension is formulated..

Edited by smashly
Link to comment
Share on other sites

[RESOLVED] John/Smashy it works fine now. Thanks a million.

This is the final code

#Include <File.Au3>
#Include <String.Au3>
$iScanFile = @ScriptDir & '\CEREIndex.txt'
$iScanFolder = @ScriptDir & '\CERESOFT-P'
$iResultFolder = @ScriptDir & '\Result'
If DirGetSize ($iResultFolder) = '-1' Then DirCreate ($iResultFolder)
For $A = '1' To _FileCountLines ($iScanFile)
$Split = FileReadLine ($iScanFile, $A)
$Split = StringSplit ($Split, '|')
$Name = _GetCorrectName ($Split['1'])
$Type = _FileGetType ($Split['4'])
$New = $iResultFolder & '\' & $Name & $Type
$File = $iScanFolder & '\' & $Split['4']
FileCopy ($File, $New, '1')
Next


Func _GetCorrectName ($iData)
$iString = ('A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z')

$iString = StringSplit ($iString, '|')

    $sRet = $iData
    While (StringLeft($iData, 1) = "0" And StringLen($sRet) > 13)
        $sRet = StringTrimLeft($sRet, 1)
    WEnd
    $sRet = StringLeft($sRet, 9) & StringMid($sRet, StringInStr($sRet, ".", 0, -1))
    $ireturn = $sRet
    
    

Return StringLeft ($iReturn, '9')



Return $iReturn

EndFunc


Func _FileGetType ($iFile)
$String = _StringReverse ($iFile)
$String = StringSplit ($String, '.')
$String = '.' & _StringReverse ($String['1'])
Return $String
EndFunc
Edited by Santana

Just another special date with a different challenge

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