python: Reading and searching .txt files

Question:

So I think I am almost there. I am searching a poker hand history txt document counting the number of hands.

At the start of each hand we have this statment “Game #xxxxxx starts.”

I am looking the word “starts.” present at the start of each hand so I wanted to count all the occurrences of this.

Hands_Played is always returning as 0 so I think the word I am looking for is not being picked up properly

Any ideas what I’m doing wrong?

Hands_Played = 0

def CountHands(Hands_Played):
    Hand_History_File = open("C:xxxxxblah_blah.txt", "r")
    data = Hand_History_File.read()
    print data
    print "Counting Hands..."
    for line in data:
        print "Loop" #Shows me that each line is being read
        if "starts." in Hand_History_File:
            Hands_Played = Hands_Played + 1
    return Hands_Played            

CountHands(Hands_Played)
print "Number of Hands Played: %s" % Hands_Played
Asked By: Behzad

||

Answers:

Update:

You also need to assign the return value from the function to a variable before you can use it subsequently:

CountHands(Hands_Played)
print "Number of Hands Played: %s" % Hands_Played

Should be

Hands_Played = CountHands(Hands_Played)
print "Number of Hands Played: %s" % Hands_Played

Otherwise you never receive the count, and you just end up displaying the initial value you set at the start of the program (0).

For that matter, unless you are maintaining a count between function calls, you don’t really need a parameter for this function. Just create the Hand_Played variable locally inside, at the start of the function, and return it as you do now. You can remove the parameter from your function header and your call and you should be all set.

previous, still applies.

Instead of:

if "starts." in Hand_History_File:

you probably want

if "starts." in line:

Also, don’t forget to explicitly close the file when you are done with it. I.e., make a call Hand_History_File.close() before you return from the function.

Better yet, consider using the with construct to manage you files. It will close your files for you automagically at the end of the block when you are done with it, or you encounter an exception. And you could also process your file line-by-line and simplify your code some more. I.e., a streamlined version, close to your original design of your function/code:

def CountHands():
    Hands_Played = 0
    with open(r"C:xxxxxblah_blah.txt") as Hand_History_File:
       for line in Hand_History_File:  # process file line-by-line
           if "starts." in line:
              Hands_Played +=  1
    return Hands_Played


Hands_Played = CountHands()
print "Number of Hands Played: %s" % Hands_Played

Notes:

I use a "raw" string (with the ‘r‘ in front of your path) to prevent Python from interpreting certain characters combinations the string. I don’t use "r" in the open call as it’s the default when opening files. I use the += operator to shorten your increment. And your file is closed when you leave the block started with with.

Answered By: Levon

why not let python do the counting itself ?

def CountHands(Hands_Played):
    with open("C:xxxxxblah_blah.txt", "r") as Hand_History_File:
        Hands_Played += Hand_History_File.read().count("starts.")
    return Hands_Played            

What you’re doing wrong in your code, is :

  1. you should use the if "starts." in Hand_History_File, here you check the existence of “starts.” in your file handle, not in the content of the file

  2. you use the same variable name as a global and parameter name. Thus, the parameter modified in the function is not the global one, only a copy of it. To correct this try to print what your CountHands() call returns

Answered By: Cédric Julien

This is how you iterate over a file:

with open('workfile') as f:
    for line in f:
        print line,
        # do something
Answered By: zenpoy

The problem is that you are not using scope correctly. The problem is that python is interpreting the Hands_Played that the function takes in and the Hands_Played outside the function as different variables. Look at the code below:

>>>variable = 10
>>>def addOne(variable):
    variable += 1
    return variable

>>>variable
10
>>>addOne(variable)
11
>>>variable
10

You can fix this by replacing CountHands(Hands_Played) with the statement Hands_Played = CountHands(Hands_Played).

Answered By: Rob Volgman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.