I am beginning to code with python. I have run into this problem. I am searching for a string in my file handle variable by creating a function for that. But everytime I iterate through the lines in the file handle variable and pass it on to the function the variable I use for count in the function initializes with 0. Is there a way through to capture the number of times a string appears in a file, by defining a function instead of counting in the main program. Thankyou.
func, you are redefining the variable
c each time it runs:
So I suppose your code prints:
1 1 1 1 1
If that’s true, you have to define
c once. Maybe outside of the function?
Also, it prints when you don’t find the expected string. I tried an example and got:
1 0 0 1 1 0 1 0
(The values may vary, but that’s an example)
You may want to store the
c variable, but don’t print until you finish the loop.
Another option could be an
if statement, and modify the
def func(a): a=a.strip() if "Temp" in a: # use a bool instead of a number return True return False fhand = open("your_file_name") # replace with your filename count=0 # we'll use this variable for i in fhand: # use an if statement if func(i) is True: count+=1 print(count)
For me, this is the best solution.
First we have to talk about elephant in the room - this code does not capture number of times string appears in a file. It captures lines where string is present. There could be one, two or gazillion appearances of the string on single line.
Then there are othe things.
It is not good practice to post pictures of code. Why this is not good? In order to run code one must manually enter it from picture instead of copying from your post. There are simple ⌘ + A (select all), ⌘ + C (copy), ⌘ + V (paste) (on Windows instead of ⌘ use CTRL) what can be used in most text editors to copy-and-paste the code.
There is no need to strip a line. It will not interfere with counting.