Jump to content

Knowing if a file exists


mr-es335
 Share

Recommended Posts

Good day,

There are two functions involved here:
1) Func _AddToList()
2) _CreateShowFile()

This program is "really-and-truly" a glorified Playlist program [Playlist Maker] coded by ragnarok775 [Link]. Much of the original script was updated by Updated script by Andreik...thanks to you both!

In the list creation-process, I select pre-created data files [called .edl files] which are combined into what is called a "SET". The contents of this SET are then stored in an .ini file for later retrieval. This .ini file is stored in a specific location [Master_Backup\Shows].

To be able to actually use this SET, a .shw data file is required, which is not actually created until later. This .shw data file is akin to creating a playlist in an audio player application [such as Foobar].

My main issue is that the .shw file is created "after-the-fact" - after the .ini file is created. This .shw file needs to be added to the .ini file to make the SET "complete" [which is now called a "SHOW"]. This .shw fie must also to be stored in the above location [Master_Backup\Shows] for later retrieval.

The three main issues that I have been attempting - without any "real" success, to rectify then are...

1) Determining if there is a pre-existing .shw file
* See: _AddToList(), SECTION A

2) Making a copy of an empty .shw file that is renamed to the name of SET
* See: _CreateShowFile(), SECTION B

3) Having the _AddToList() function knowing that a .shw file already exists - so that I not asked "Is there a SHOW file?" each-and-every-time I return to the _AddToList() function.

I have attached a completed script that is functional, along with a sample .edl required for the SET.

sample.au3IO_Session_1.edl

The Data Paths
There are three data paths involved here:

1) Local $WorkingDir = "G:\Software\AutoIt\Errors\New folder\Initial"
• The location of the .edl files

2) Local $SrcFilename = "E:\Master_Backup\Shows\Master_Show.shw"
• The location of the .shw file that is copied, see #2 above

3) Local $DstFilePath = "E:\Master_Backup\Shows"
• The "backup" location for .ini and .shw data files

What I require is some means of letting the _AddToList() function knows that a .shw already exists. I do hope that this makes sense? I also hope that the title of this post adequately explains the "issue"?

Any assistance in this matter would be greatly appreciated!

Notes
1. One idea is to have the means of being able to continue selecting files until no more are required. An "Are you done?" prompt could be invoked - thus preventing the "Is there a SHOW file?" prompt from repeatedly occurring.
2. Or a counter of some sort?
3. Of, if I have been asked, do not ask again?
4. What would be ideal - which I attempted to do without any apparent success, is to have the _CreateShowFile() function add the .shw file to the .ini file immediately after the name is input.

Edited by mr-es335
Additions to "Notes"
Link to comment
Share on other sites

have you noticed there is AutoIt internal function FileExists() ?

i trust the other File* functions would come in handy too.

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

orbs,

Of course I have looked at that Function. However, have you looked at the provided sample code?

1. Func _AddToList() calls _CreateShowFile()
2. _CreateShowFile() contais two variable, 1) $SetName and b) $UpdatedPath
• SetName = Input name
• $UpdatedPath = The path of the Input filename
3. Do I not need to return that value back to _AddToList()?
4. If so, how is this accomplished?

This works...

Local Const $sFilePath = "E:\Master_Backup\Shows\EC.shw"
    ;Local $sFilePath = $SetName
    Local $iFileExists = FileExists($sFilePath)
    If $iFileExists Then
        MsgBox($MB_SYSTEMMODAL, "", "The file exists." & @CRLF & "FileExist returned: " & $iFileExists)
    Else
        MsgBox($MB_SYSTEMMODAL, "", "The file doesn't exist." & @CRLF & "FileExist returned: " & $iFileExists)
    EndIf

...however...this does not...

Local Const $sFilePath = $UpdatedPath ; The variable from _CreateShowFile()
    ;Local $sFilePath = $SetName
    Local $iFileExists = FileExists($sFilePath)
    If $iFileExists Then
        MsgBox($MB_SYSTEMMODAL, "", "The file exists." & @CRLF & "FileExist returned: " & $iFileExists)
    Else
        MsgBox($MB_SYSTEMMODAL, "", "The file doesn't exist." & @CRLF & "FileExist returned: " & $iFileExists)
    EndIf

I gather the questions is: "How do I get UpdatedPath back to _AddToList()?"

Edited by mr-es335
Link to comment
Share on other sites

12 hours ago, mr-es335 said:

What I require is some means of letting the _AddToList() function knows that a .shw already exists.

does your function already know the name of the desired .shw file, or are you willing to accept any file with the .shw extension as valid?

 

 

 

also, the snippet you described that does not work, 1) where is it supposed to fit in your program? 2) the $UpdatedPath variable is Local to function _CreateShowFile(), so inaccessible to the calling script. either make it Global, or Return that variable from the function to the calling script. add this line as the last line of _CreateShowFile():   (just before the EndFunc line)

Return $UpdatedPath

and when calling the function from the script, line 36, do like this: 

$UpdatedPath = _CreateShowFile($ListView)

(of course, declare a Local $UpdatedPath in _AddToList(), and use it later on.)

these two statements combined, allow the value from _CreateShowFile() to be used in _AddToList().

Edited by orbs

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

orbs,

Would the following be correct thus far?

;-----------------------------------------------
Func _AddToList($ListView)
    Local $UpdatedPath = _CreateShowFile($ListView) ; The Local variable
    ;-----------------
    Local $MyBox = MsgBox(4, "Is there a SHOW file?", "Yes or No")
    If $MyBox == 7 Then
        $UpdatedPath = _CreateShowFile($ListView) ; Updated
    ElseIf $MyBox == 6 Then
    EndIf
EndFunc   ;==>_AddToList
; -----------------
Func _CreateShowFile($ListView)
    Return $UpdatedPath ; The return
EndFunc   ;==>_CreateShowFile
;-----------------------------------------------

If the above IS correct...then I gather I need to know where exactly to position this script?

If $UpdatedPath Then
    MsgBox($MB_SYSTEMMODAL, "", $UpdatedPath)
Else
    MsgBox($MB_SYSTEMMODAL, "", $UpdatedPath)
EndIf

 

Edited by mr-es335
Link to comment
Share on other sites

you should not be needing to call _CreateShowFile() twice.

i thought you wanted to avoid the need of asking the user for a SHOW file, so the MsgBox() section, along with the second call to _CreateShowFile(), becomes  completely unnecessary.

as for the second snippet, what does it do? you execute the same command whether $UpdatedFile is or isn't... if it's for debug, then skip the condition check and put only the MsgBox line immediately after you get the value from _CreateShowFile().

 

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

ods,

I have been attempting to use the suggestions you provided, but I am at a complete loss in knowing just how to implements these!

You stated:
1) Add this line as the last line of _CreateShowFile() - just before the EndFunc line: Return $UpdatedPath <== Done!
2) And when calling the function from the script, line 36, do like this: $UpdatedPath = _CreateShowFile($ListView)
• Of course, declare a Local $UpdatedPath in _AddToList(), and use it later on <== Not really sure what you mean here!
3) These two statements combined, allow the value from _CreateShowFile() to be used in _AddToList() <== Though I understand the reasoning behind this, I simply cannot see how this actual "works"?

Help?!

Link to comment
Share on other sites

ods,

How is this...

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

Example()

Func Example()
    Local $File = DoesFileExist()
    If FileExists($File) Then
        YesFileExists()
    Else
        MsgBox(0, "File", "File does not exist!")
    EndIf
EndFunc   ;==>Example

Func DoesFileExist()
    Local $DstFilePath = "E:\Master_Backup\Shows"
    ; Here is the file...
    $SetName = "EC"
    Local $File = $DstFilePath & "\" & $SetName & ".shw"
    Return $File
EndFunc

Func YesFileExists()
    MsgBox(0, "File", "File exists!")
EndFunc

This DOES NOT work however...

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

Example()

Func Example()
    Local $File = DoesFileExist()
    If FileExists($File) Then
        YesFileExists()
    Else
        MsgBox(0, "File", "File does not exist!")
    EndIf
EndFunc   ;==>Example

Func DoesFileExist()
    Local $DstFilePath = "E:\Master_Backup\Shows"
    ; Here is the file...
    $SetName = InputBox("Notice!", "Please enter the SET name...") ; Added
    Local $File = $DstFilePath & "\" & $SetName & ".shw"
    Return $File
EndFunc

Func YesFileExists()
    MsgBox(0, "File", "File exists!")
EndFunc

 

Edited by mr-es335
Link to comment
Share on other sites

Good day,

Following is a possible solution,

;-----------------------------------------------
Func CheckForShowFile($ListView) ; Created a separate function
    ;Check for SHOW file
    Local $MyBox = MsgBox(4, "Is there a SHOW file?", "Yes or No")
    If $MyBox == 7 Then
        _CreateShowFile($ListView)
    ElseIf $MyBox == 6 Then
        _AddToList($ListView)
    EndIf
EndFunc   ;==>_AddToList
;-----------------------------------------------
Func _AddToList($ListView)
    Local $WorkingDir = 'E:\Master_Backup'
    Local $iItem
    Local $sFileSelectDialog = FileOpenDialog('Select Session Files', $WorkingDir, 'Data Files (*.edl; *.shw)', 4)
    If @error Then Return SetError(1, 0, Null)
    Local $aSplit = StringSplit($sFileSelectDialog, '|')
    If Not IsArray($aSplit) Then Return SetError(1, 0, Null)
    If $aSplit[0] = 1 Then
        $iItem = _GUICtrlListView_FindText($ListView, $aSplit[1], -1, False)
        If $iItem = -1 Then
            GUICtrlCreateListViewItem($aSplit[1], $ListView)
        Else
            MsgBox(0x40, 'Info!!', $aSplit[1] & ' is already in the Session Listing.')
        EndIf
    Else
        _GUICtrlListView_BeginUpdate($ListView)
        For $Index = 2 To $aSplit[0]
            $iItem = _GUICtrlListView_FindText($ListView, $aSplit[1] & '\' & $aSplit[$Index], -1, False)
            If $iItem = -1 Then
                GUICtrlCreateListViewItem($aSplit[1] & '\' & $aSplit[$Index], $ListView)
            Else
                MsgBox(0x40, 'Info!', $aSplit[1] & '\' & $aSplit[$Index] & ' is already in the Session Listing.')
            EndIf
        Next
        _GUICtrlListView_EndUpdate($ListView)
    EndIf
    _AddToList($ListView) ; Return to _AddToList function
EndFunc   ;==>_AddToList
;-----------------------------------------------
Func _CreateShowFile($ListView)
    Local $SrcFilename = "E:\Master_Backup\Shows\Master_Show.shw"
    Local $DstFilePath = "E:\Master_Backup\Shows"
    ; If SET, then enter SET name
    Global $SetName = InputBox("Notice!", "Please enter the SET name...")
    ; Add SET name to $DstFilePath
    Local $UpdatedPath = $DstFilePath & "\" & $SetName & ".shw"
    FileCopy($SrcFilename, $UpdatedPath, $FC_OVERWRITE)
EndFunc   ;==>_CreateShowFile
;-----------------------------------------------

Observations
1) So, I create a separate function for CheckForShowFile()
2) Added _AddToList() to "Yes" response
3) Added a return to AddToList()
• Note: Not too sure if this an acceptable practice or not...could be construed as a Goto?

Anyhow...comment/suggestions?

Edited by mr-es335
Link to comment
Share on other sites

6 hours ago, mr-es335 said:


• Note: Not too sure if this an acceptable practice or not...could be construed as a Goto?

this is most definitely NOT the way to do it, and it wouldn't take more than a few calls to _AddToList() to figure out why. calling a function from within itself, as often called "recursion", is used in a different manner, for different reasons. NOT what you are doing. "Goto" is also a poor scripting strategy, and no wonder modern scripting languages (AutoIt included) do not support it altogether.

the way to go is using a loop.

1) first, declare all your Local variables at the top of the functions (not whenever you first assign a value to them).

2) then, consider the code starting with this line:

$sFileSelectDialog = FileOpenDialog('Select Session Files', $WorkingDir, 'Data Files (*.edl; *.shw)', 4)

until the end of the function (excluding the last call to  _AddToList(), which should be removed).

3) enclose all this section in a loop, like this:

Do

{the said section of code}

Until {whatever condition you choose to end the function and return to the calling script, or False if you never do}

 

also, don't have a Global variable $SetName declared inside a function _CreateShowFile(). and, as you have already discovered, if the user does not input anything in the inputbox, you'd have an invalid file name to work with. so test for valid input.

 

flogging aside 🙂 , you might want to employ a few best practices . this is not an easy reading, especially for non-native English speakers; but it is worthwhile. i would highly recommend for start, give your variables meaningful names, and put comments wherever adequate. consider this: if in six months time you'd be revisiting that code, would you understand what's going on?

 

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

You could also use the FileSaveDialog at the beginning of the script so the user can select the Show file or create a new one, basic example:

;-----------------------------------------------
#include <File.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
;-----------------------------------------------
Global $g_sMasterShow = "D:\Master_Backup\Shows\Master_Show.shw"
Global $g_sWorkingDir = "D:\Master_Backup"
Global $g_sShwFileDir = $g_sWorkingDir & "\Shows"
Global $g_sShwFileName = @YEAR&"-"&@MON&"-"&@MDAY&"_SHOW.shw"
Global $g_sShwFilePath, $g_bShwFilePath = False

Global $g_hGUI = GUICreate("Session List Producer", 940, 255)
    GUISetFont(12, 800, 0, "Calibri")
;-----------------------------------------------
    Global $g_idAddToList = GUICtrlCreateButton("Add to List", 10, 10, 200, 25)
    Global $g_idListView = GUICtrlCreateListView("Current Session Files Listing", 220, 10, 500, 235, 0x0008, 0x00000020)
        _GUICtrlListView_SetColumnWidth($g_idListView, 0, 500)
    Global $g_idExitMe = GUICtrlCreateButton("Exit", 10, 40, 200, 25)

_AddToList()

;-----------------------------------------------
GUISetState(@SW_SHOW, $g_hGUI)
;-----------------------------------------------
While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $g_idAddToList
            _AddToList()
        Case $g_idExitMe
            Exit
    EndSwitch
WEnd
;-----------------------------------------------
Func _AddToList()
    ; SECTION A
    ; Check if Show File Path equals false, dialog only appears once
    ;-----------------
    If Not $g_bShwFilePath Then
        $g_sShwFilePath = FileSaveDialog("Select a SHOW File", $g_sShwFileDir, "SHOW(*.shw)",0,$g_sShwFileName)
        If @error Then Exit MsgBox(4096, "Error", "No file was selected")
        If Not FileExists($g_sShwFilePath) Then FileCopy($g_sMasterShow, $g_sShwFilePath, 1)
        $g_sShwFileName = StringTrimLeft($g_sShwFilePath,StringInStr($g_sShwFilePath,"\",0,-1))
    EndIf
    ;~ Show File Path has been set
    $g_bShwFilePath = True
    ;-----------------
    Local $iItem
    Local $sFileSelectDialog = FileOpenDialog('Select Session Files', $g_sWorkingDir, 'Session Files (*.edl)', 4)
    If @error Then Return SetError(1, 0, Null)
    Local $aSplit = StringSplit($sFileSelectDialog,'|', 2)
    If Not IsArray($aSplit) Then Return SetError(1, 0, Null)
    If UBound($aSplit) = 1 Then
        _GUICtrlListView_FindText($g_idListView, $aSplit[0], -1, False)
    Else
        For $i = 1 To UBound($aSplit) - 1
            If _GUICtrlListView_FindText($g_idListView, $aSplit[0] & "\" & $aSplit[$i], -1, False) = -1 Then GUICtrlCreateListViewItem($aSplit[0] & "\" & $aSplit[$i], $g_idListView)
        Next
    EndIf
EndFunc   ;==>_AddToList

 

Link to comment
Share on other sites

orbs,
You stated, "...this is most definitely NOT the way to do it..."
• At least I DID acknowledge that fact...thanks for the reminder however.

You then stated, "...the way to go is using a loop..."
• As a point-if-interest, I tend to find it interesting to-say-the-least, that though I do consider myself as "procedural", I do not believe myself to be "logical"! Thus my ignorance and seeming obliviousness in the use of "loops".
• procedural: "...particular action or mode of conducting an action..."
• logical: "...following as a reasonable consequence..."

The use of the Global variable for $SetName was an error…which has been thus, corrected.

And then you stated, "…you might want to employ a few best practices..." I have updated all of my code to 1) place "_'s" before all User Functions, 2) the Use of Upper/Lowercase letters for Variables and Functions, and 3) attempting to do my best at coming up with "meaningful names" – though such usage being highly a subjective one.

Regarding the comments, though maybe NOT the best practice. I use Excel for much of my coding – using "links" to explain what it is tat I am doing.  In short, I DO understand the Importance of "comments"…or "REMarks"!

Lastly, "...this is not an easy reading..."...may I ask what "this " is in reference to? Is such in reference to the actual "coding" or to the "explanations"?

Thanks for the all of your assistance thus far...very much appreciated!

PS: After perusing and noting the information as provided the in "Best Practices" information...though such information is indeed "practicable"...how many in THIS Forum actually implement such "practices"? Not many...from what I have observed!

Mr_Bean.jpg.be29c383d57a012aac84bb4d9fe6d4e7.jpg

Edited by mr-es335
Link to comment
Share on other sites

Subz,

Firstly, thanks for the script...interesting...[as long as I can get my head around it!]

Secondly, the script is missing tow very important "things:"
Thing #1) I require also the selection of a .shw file as well ['Data Files (*.edl; *.shw)']
Thing #2) I need to have the selection of data continue until "Cancel" is selected

I hope this makes sense?

Link to comment
Share on other sites

orbs,

Is "this" what you are suggesting?...

;-----------------------------------------------
Func _AddToList($ListView)
    ;1) first, declare all your Local variables at the top of the functions (not whenever you first assign a value to them).
    Local $WorkingDir = ''
    Local $iItem = 0
    Local $sFileSelectDialog = ''
    Local $aSplit = 0
    ;3) enclose all this section in a loop, like this:
    Do
        ;2) then, consider the code starting with this line:
        $sFileSelectDialog = FileOpenDialog('Select Session Files', $WorkingDir, 'Data Files (*.edl; *.shw)', 4)
        ;{the said section of code}
        If @error Then Return SetError(1, 0, Null)
        Local $aSplit = StringSplit($sFileSelectDialog, '|')

        If Not IsArray($aSplit) Then Return SetError(1, 0, Null)
        If $aSplit[0] = 1 Then
            $iItem = _GUICtrlListView_FindText($ListView, $aSplit[1], -1, False)
            If $iItem = -1 Then
                GUICtrlCreateListViewItem($aSplit[1], $ListView)
            Else
                MsgBox(0x40, 'Info!!', $aSplit[1] & ' is already in the Session Listing.')
            EndIf
        Else
            _GUICtrlListView_BeginUpdate($ListView)
            For $Index = 2 To $aSplit[0]
                $iItem = _GUICtrlListView_FindText($ListView, $aSplit[1] & '\' & $aSplit[$Index], -1, False)
                If $iItem = -1 Then
                    GUICtrlCreateListViewItem($aSplit[1] & '\' & $aSplit[$Index], $ListView)
                Else
                    MsgBox(0x40, 'Info!', $aSplit[1] & '\' & $aSplit[$Index] & ' is already in the Session Listing.')
                EndIf
            Next
            _GUICtrlListView_EndUpdate($ListView)
        EndIf
        ;Until {whatever condition you choose to end the function and return to the calling script, or False if you never do}
    Until False
    ;Until ; I really have NO idea what to put here...but False appears to work??
    ;until the end of the function (excluding the last call to  _AddToList(), which should be removed).
    ;_AddToList($ListView) ; Return to _AddToList function....TO BE REMOVED...LISTED ONLY FOR REFERENCE PURPOSES!!
EndFunc   ;==>_AddToList
;-----------------------------------------------

 

Edited by mr-es335
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...