Get data from text file and Check List in List

Question:

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

Asked By: onurhanozer

||

Answers:

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")
Answered By: Mohamed Fathallah

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])
Answered By: Vincent Bénet

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
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.