xerox
xerox

Reputation: 7

Python: Reading file line by line and comparing with target

I am trying to read a file line by line from Python and comparing it with target.

Can't seem to print the both variables out:

target = 4234789247293487
counter = 0
with open("/Users/admin/Desktop/test3.txt", "r") as p:
for line in p:
    counter = counter + 1
    if line == target:
        print(line)
        print(counter)

Upvotes: 0

Views: 194

Answers (2)

Nilesh Ingle
Nilesh Ingle

Reputation: 1883

In the text file it appears those are long strings with a trailing space at the end. In the example below, the first line is changed to have the number from the target in the beginning. When the text file is read using pd.read_csv() it creates one row with multiple columns. These can then be looped over to print them out. The code below worked with given example.

Lines from the Text file

4234789247293487497892349872490564275671497636478264860567240458632746270862834678673406432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673416432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673426432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673436432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673446432783427834

Code

import numpy as np
import pandas as pd

# Initialize variables
target = 4234789247293487
counter = 0

# Read the text file
# This creates one row and multiple columns
df = pd.read_csv('/Users/erv/Desktop/test3.txt',sep=" ", header=None)

# Loop over each column
for i in range(df.shape[1]):
    line = df.iloc[0][i]
    counter = counter + 1
    #print("\n",line)
    if (str(target) in str(line)):
        print("line: {}".format(line))
        print("counter: {}".format(counter))
        print("\n")

Output

enter image description here

Upvotes: 0

Zachary822
Zachary822

Reputation: 3121

You should either do target = str(4234789247293487) or if int(line) == target:, because you are trying to compare an integer with a string.

Upvotes: 2

Related Questions