简体   繁体   English

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

[英]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. 我正在尝试从Python逐行读取文件,并将其与目标进行比较。

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)

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

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. 在下面的示例中,第一行更改为从target开始的数字。 When the text file is read using pd.read_csv() it creates one row with multiple columns. 使用pd.read_csv()读取文本文件时,它将创建一行多列的行。 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 输出量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM