如何使用python检查文本文件中是否存在数据? [英] How do I check a data exist or not in text file using python?

查看:1009
本文介绍了如何使用python检查文本文件中是否存在数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我解决这个问题吗?我得到了结果1和0,但我不知道如何将其写入文件。

Is anyone can help me to figure out this problem? I got the result 1 and 0 but I can not figure out how to write it to a file.

outfile = "Result.txt"
Array = ["6J", "xx", "ss", "11"]

with open("test.txt", "r") as f:
    with open(outfile, "w") as result:
        output_list = []
        for rec in f.read().splitlines():
            rec = rec[:-3]  
            FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)] 
            output_list.append(FBlist)
            print(output_list)

FBlist_set = set(FBlist)
Array_set = set (Array)

if Array_set & FBlist_set:
   print ("found")
   result.write("1")
else:
   print ("0")
   result.write("0")

我的test.txt文件是6J7K8L.XY,首先,我将文本文件转换为[ 6J, 7K, 8L]。最后3个字符不包括在内。为什么要转换为2个字符,因为我想比较每个2个字符,而我的固定数据也要比较2个字符。我的问题是我不知道如何使用文本文件检查固定数据并返回1或0。

My test.txt file is 6J7K8L.XY First, I convert that text file be like this ["6J", "7K", "8L"] . The 3 last characters is not include. Why I convert to 2 characters, because I want to compare it each 2 characters and my fixed data also 2 characters. My problem is I can not figure out how to check my fixed data with text file and return 1 or 0.

推荐答案

您发布的有限信息似乎总会得到0,因为您正在比较 Array (一个包含4个字符串元素的数组,每个<您附加到 output_list 数组的code> FBlist 元素。我只能想象比较看起来像这样:

With the limited info you posted it would seem as though you're getting 0 always because you're comparing Array, an array with 4 string elements, with the first 2 elements of each FBlist element you appended to the output_list array. I could only imagine the comparison looking something like this:

 ["6J", "xx", "ss", "11"] == [element1, element2]

始终为False。 aw测一下test.txt文件中的内容的示例?

which will always be False. Hoaw about a sample of what's in the test.txt file?

还: int(True) int(False)总是会分别给您1或0,因此不需要 str((0,1)[found])您可以执行 str(找到)

Also: int(True) and int(False) will always give you 1 or 0 respectively so no need for str((0,1)[found]) you can just do str(found)

编辑1:

为回应您的评论,请在代码中进行此调整,以查看要比较的内容:

In response to your comment, make this adjustment in your code to see what it is you are comparing:

for line in output_list:
    print('comparing {arr} == {line} ?'.format(arr=Array, line=line[:3])
    found = int(Array == line[:3])
    result.write(found)

从您的评论中我看到迫在眉睫的问题是, Array 有4个项目,而item [:3]有3个项目,因此它们将永远不会相同...

From your comment I see an immediate problem, Array has 4 item while item[:3] has 3 item so they will never be the same...

这篇关于如何使用python检查文本文件中是否存在数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆