繁体   English   中英

Python 检查TXT文件中的数字是否存在

[英]Python check if numbers in TXT file exists

我对为什么我的 python 脚本无法识别文本文件中肯定存在的数字有点一头雾水。

这是文本文件:

001420999;
000502999;
000120999;
000126999;
001220499;
001180000;
001104799;
001123111;

这是我正在使用的代码:

with open('/var/www/html/capcodes.txt', 'r') as f:
    capcodes = capcode.split()
    for cap in capcodes:
        if cap.strip() in f.read():
            print("true")
        else:
            print("false")

是的, capcodes已填满,他确实得到 cap.strip() 没有问题。

它变得越来越奇怪,它唯一说的是数字:“001180000”,其他的都不起作用。

.read读取整个文件。 调用一次后,您就位于文件的末尾。 在循环开始之前运行一次 read() 并将结果存储在一个变量中,因此:

with open('/var/www/html/capcodes.txt', 'r') as f:
    capcodes = capcode.split()
    stored_lines = f.read()
    for cap in capcodes:
        if cap.strip() in stored_lines:
            print("true")
        else:
            print("false")

请注意,如果您正在寻找完整的行匹配,您可能需要先进行更多清理,并将文件放入列表中:

with open('/var/www/html/capcodes.txt', 'r') as f:
    capcodes = capcode.split()
    stored_lines = [line.strip() for line in f.readlines()]
    for cap in capcodes:
        if cap.strip() in stored_lines:
            print("true")
        else:
            print("false")

...否则,如果文件中存在行 '12345',则 cap 的值 '123' 将匹配。

暂无
暂无

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

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