简体   繁体   中英

Python check if numbers in TXT file exists

I'm a bit clueless about why my python script doesn't recognize the number that is definitely in the text file.

This is the text file:

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

and this is the code i'm using:

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

Yes, capcodes is filled and he indeed gets cap.strip() without problems.

It is getting stranger, the only time it says true is with number: "001180000" the other ones don't work.

.read reads the entire file. After calling it once, you're at the end of the file. Run read() once before the start of the loop and store the result in a variable, so:

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

Note that if you're looking for a full line match, you might want to do some more cleanup first, and make the file into a list:

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

...since otherwise, a value of '123' for cap will match if a line '12345' is in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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