我正在尝试从Python逐行读取文件并将其与目标进行比较。
似乎无法同时打印出两个变量:
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)
答案 0 :(得分:2)
您应该执行target = str(4234789247293487)
或if int(line) == target:
,因为您正在尝试将整数与字符串进行比较。
答案 1 :(得分:0)
在文本文件中,显示的是那些很长的字符串,末尾带有空格。在下面的示例中,第一行更改为从target
开始的数字。使用pd.read_csv()
读取文本文件时,它将创建一行多列的行。然后可以将它们循环以打印出来。下面的代码适用于给定的示例。
文本文件中的行
4234789247293487497892349872490564275671497636478264860567240458632746270862834678673406432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673416432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673426432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673436432783427834 4234789207293487497892349872490564275671497636478264860567240458632746270862834678673446432783427834
代码
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")
输出