Not able to close the text file in main script when opened in def()

Asked by Milind Warade

Hi,

I want to write the text file when I have used array.
It was giving me error as :
 my_file.close()
NameError: name 'my_file' is not defined

==============================================

Check the code:
# Game ended
def Employee(event):
    wait(1)
    click("FEmployeeCod-9.png")
    wait(1)
    type(event.region.currentTimeEntry)
    wait(1)
    el = "\n" # the end of line you want to use
    my_file=file("D:\DPTT_XML\DPWrite.txt", "w")
    if exists ("ULUNPAID-7.png"):
        type("UL")
        my_file.write("UL"+el) # if you want to have line breaks
        wait(2)
    if exists ("WOWEEKLYOFF-7.png"):
        type("WO")
        my_file.write("WO"+el) # if you want to have line breaks
        wait(2)
    wait(1)
# Main function
# Go to Portal for checking Employee Attendance report
import array
DPRead=[]
f=open("D:\\DPTT_XML\\DPRead.txt","r")
fout = open("D:\\DPTT_XML\\DPRead-results.txt","w")

for line in f.readlines():
    DPRead.append(line.strip()) # get rid of newline
f.close()
wait(2)
click("1348813496420-5.png")
wait(5)
click("earthprogram-5.png")
type("firefox" + Key.ENTER)
wait(5)
type("t", KeyModifier.CTRL)
wait(10)
type("https://localhost:9080/index.action" + Key.ENTER)
wait("LoginUsernam-5.png",20)
click("Username-5.png")
type("ABCD")
click("Password-5.png")
type("1234")
wait(2)
# Employee code for E1 : abhileft1
wait(2)
SCREEN.currentTimeEntry = DPRead[2]
onAppear("FEmployeeCod-9.png", Employee)
observe(50)
wait(1)
# Employee code for E1 : abhileft2
click("VEmployeeCod.png")
wait(2)
SCREEN.currentTimeEntry = DPRead[3]
onAppear("FEmployeeCod-9.png", Employee)
observe(50)
my_file.close() # ERROR OCCURS AT THIS STAGE
wait(2)
App.close("Firefox")
wait(3)

Please do needful help.

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
Best RaiMan (raimund-hocke) said :
#1

my_file is only known in the local context of the handler.

So you should simply define/open it in the main script before the first observe, then it is known (global) in the def.

Revision history for this message
Milind Warade (warademilind) said :
#2

Thanks RaiMan, that solved my question.