Felipe Melo wrote: > Hello, > > I want to read the below matrix, identify when the characters in front of > "want = " are equal to "1" and then save in an array and in an output file > the characters above. But I don't know how to identify the second line and > store in a variable: > > alpha=0 beta=2 gamma=50 > want = 0 > alpha=0 beta=2 gamma=50 > want = 1 > alpha=0 beta=2 gamma=50 > want = 0 > alpha=0 beta=2 gamma=50 > want = 1 > alpha=0 beta=2 gamma=50 > want = 0 > > > This is part of the code: > > try: > datadir = '/home/me/Test_python/' > > fileHandle = open( "%s/teste.txt"%datadir, 'r' > ) > vector = [ ] > for line in fileHandle.readlines(): > line=line.strip() > a = line.split(" ")[0] > print a > b = line.split(" ")[1] > print b > c = line.split(" ")[2] > print c > d = line.split(" ")[3] > print d > if d == "1": > vector.append([a,b,c]) > n = n + 1 > fileHandle.close() > file = open("saida.txt","w") > for cont in range(n): > file.write = vector > > > except: > print "Exception" > sys.exit( 1 ) > > > When I execute the code there is an error when the loop finds the second > line > > > [felipe@grumari Test_python]$ python verificar.py > alpha=0 > beta=2 > gamma=50 > Exception
Felipe you're shooting yourself in the foot when you put the try: ... # error occurs here except: # catch everything ... # show a generic message around the part of the code that does the actual work. Remove the try...except, and see if you can make sense of the traceback and the error message you get. The message will say what exactly went wrong, and the traceback will show where it went wrong. If with this valuable information you still cannot fix the code yourself come back here, but this time post the traceback (use copy and paste, don't rephrase) to make it easier for us to help you fix the bug. Random hints: - your code seems to expect > alpha=0 beta=2 gamma=50 > want = 0 on a single line. Either adjust the data or the code. - writing to a file is spelt file.write(some_string) - you can iterate over lists, no need for range(): for item in items: ... # do something with item - you can iterate over files, no need for readlines(): for line in file: ... # do something with line _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor