Python:逐行读取文件并与目标进行比较

问题描述 投票:0回答:2

我试图从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)
python if-statement conditional
2个回答
2
投票

您应该执行target = str(4234789247293487)if int(line) == target:,因为您试图将整数与字符串进行比较。


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")

产量

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.