Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7.2 Multiple Values for one variable

Tags:

python

I run my own business from home and started use Python 2 days ago. I'm trying to write a script that will search through my log files line by line and tell me if a system doesn't match my mandatory naming scheme. There are multiple different schemes and I want the script to look for them all. I've tried using a list (as seen below) but that won't work and then I tried with normal brackets and that gave me an error (requires left operand, not tuple). I've noted the lines that give me a problem.

    #variables
    tag = ["DATA-", "MARK", "MOM", "WORK-"] #THIS ONE!!!!!!

    #User Input
    print "Please select Day of the week"
    print "1. Monday"
    print "2. Tuesday"
    print "3. Wednesday"
    print "4. Thursday"
    print "5. Friday"
    print "6. Saturday"
    print "7. Sunday"
    day = input("> ")

    #open appropriate file and check to see if 'tag' is present in each line
    #then, if it doesn't, print the line out.
    if day == 1:
        f = open('F:\DhcpSrvLog-Mon.log', 'r')
        for line in f:
                if tag in line:  #THIS ONE!!!!!!!!!!!!!
                        pass
                else:
                        print line 

Any tips or tricks would be most appreciated!

like image 663
user1197368 Avatar asked Mar 24 '26 23:03

user1197368


1 Answers

I suggest rewriting the code like this:

with open('F:\DhcpSrvLog-Mon.log', 'rU') as f:
    for line in f:
        for t in tag:
            if t in line: break
        else:
            print line

Using with you automagically close the file on exit of the block, so you needn't worry about forgetting to close it. Using else: in the for loop only triggers if you don't break out of the loop earlier.

like image 163
hochl Avatar answered Mar 26 '26 11:03

hochl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!