Home > Back-end >  Get data from text file and Check List in List
Get data from text file and Check List in List

Time:09-11

sorry maybe it is a very easy question but i can't find it. i have a text file and it has a data

[3, 1, 1, 1, 3, 3, 3, 3]
[1, 1, 1, 1, 3, 3, 3, 3]

in it.

I want to read this file, add all this data in one array. after this i want to check it with

with open("data.txt", "r") as fd:
    lines = fd.read().splitlines()


print(lines)

games = [3, 1, 1, 1, 3, 3, 3, 3]
print(type(lines))

if lines in games:
    print("OK")
else:
    print("NO")

I can see lines is a list, games is a list, but i can't find it in lines list.

May you help me pls

CodePudding user response:

I think this is what you want you can't check if the list exists in one array I suppose you want to check if games exist in the file or not

 with open('data.txt') as f:
       l=[ line.strip() for line in f.readlines()]
    
    print(l)
    games = '[3, 1, 1, 1, 3, 3, 3, 3]'
    print(type(l))
    if games in l:
        print("OK")
    else:
        print("NO")

CodePudding user response:

This should works with one line:

games = [3, 1, 1, 1, 3, 3, 3, 3]    
print(["NO", "OK"][sum([str(games) ==  line for line in open(r'data.txt').readlines()])>0])

CodePudding user response:

If you only want to check lines is equals games and not games in lines, this should work:

games = [3, 1, 1, 1, 3, 3, 3, 3]

with open("data.txt") as fd:
    for lines in fd.read().splitlines():
        print(f'{lines} OK') if lines == str(games) else print(f'{lines} NO')

# [3, 1, 1, 1, 3, 3, 3, 3] OK
# [1, 1, 1, 1, 3, 3, 3, 3] NO
  • Related