error in reading Text file

Asked by Dinesh Pawar on 2017-06-28

I am little new to sikuli and python, I am read a text file (text2.txt)
my programming decision depend on first line of this text file
if first line is "Done" then this file is wrong.
if first line is other than "Done" so program call some function and run it

but problem is that when this text line contain only one line "Done" then it work and exit program after popup,
if by mistake there is one more line in text file(first line is "Done") program can not exit
 I really appreciate for help.

(sorry if any mistake in Description , If you don't get I can brief here once again)

Here is my code

##############################################################################

f = open("c:/tool/Text2.txt", "r")
sumlist = []
for line in f.readlines():
    sumlist.append(str(line))

    print (line)
f.close()
kk = sumlist[0]
kk = str(kk)
popup(kk)
if kk == "Done":
    popup("Wrong Database is created Fill all required cell in Excel and run tool again", "DataBase" )
    exit(1)
else:
#call some function

#############################################################################

Question information

Language:
English Edit question
Status:
Solved
For:
Sikuli Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
2017-06-28
Last query:
2017-06-28
Last reply:
2017-06-28
RaiMan (raimund-hocke) said : #1

the function str() is not needed, because you already get strings from the file

f = open("c:/tool/Text2.txt", "r")
sumlist = []
for line in f.readlines():
    sumlist.append(line.strip()) # get rid of leading/trailing whitespace
    print (line)
f.close()
kk = sumlist[0]
popup(kk)
if kk == "Done":
    popup("Wrong Database is created Fill all required cell in Excel and run tool again", "DataBase" )
    exit(1)
else:
    #call some function

... but I do not understand your question:
This script will always exit, if 1st line is "Done", no matter how many lines follow.

Dinesh Pawar (dineshpawar22) said : #2

@Thanks RaiMan for your quick response.

As per your suggestion I make change in (4th line , where you add comment ) Script and it's work .

I am little bit interested why it occur, if you have time you can brief.

Thank you so much....

Best RaiMan (raimund-hocke) said : #3

f.readlines() iterates over the lines in the file, but each line contains all characters including the linefeed (\n or \r\n).
strip() is the easiest way, to only get the text of the line, since it removes all whitespace characters (https://en.wikipedia.org/wiki/Whitespace_character) from both ends of a line.

Hence, if you have more than one line in a file each line (except maybe the last one) has a linefeed at the end.

Dinesh Pawar (dineshpawar22) said : #4

Thanks RaiMan, that solved my question.