skip to Main Content
import json
with open('/home/sentry/Documents/mark.txt', 'r') as f1,open('/home/sentry/Downloads/axtscz-english-first-names/Male.json', 'r') as f2:

  content = f1.read()
  data = json.load(f2)
  
for p_id in data:
    name = p_id.get('name')
    
    if name in content:  # This is where my problem is.
             print('True')
    else:
             print(content)
             print (name)

The console will output both the text file each name in json file though all i want is a yes no answer.
mark.txt contains MY NAME IS MARK THANK YOU.
sorry about the capitals but the json files names are all capitals.

I have tried googling opening two files at once, but being a newbie im stumped why its not working.

2

Answers


  1. Chosen as BEST ANSWER

    import json

    with open('/home/sentry/Documents/mark.txt', 'r') as f1,open('/home/sentry/Downloads/axtscz-english-first-names/Male.json', 'r') as f2: content = f1.read() data = json.load(f2)

    for p_id in data: name = p_id.get('name') if name in content: print('Name exist') print (name)


  2. Given you current format of data I would reshape it from a list of json into either a set() or a dict().

    Given:

    data = [
        {'name': 'JAMES', 'gender': 'M', 'culture': 'EN'},
        {'name': 'MARK', 'gender': 'M', 'culture': 'EN'},
    ]
    

    A set() would look like:

    data_lookup = set(row["name"] for row in data)
    

    the dict() version might look like:

    data_lookup = {row["name"]: row for row in data}
    

    In either case from there you can use the lookup to answer if a name in in it:

    data = [
        {'name': 'JAMES', 'gender': 'M', 'culture': 'EN'},
        {'name': 'MARK', 'gender': 'M', 'culture': 'EN'},
    ]
    data_lookup = set(row["name"] for row in data)
    
    print("Yes" if "MARK" in data_lookup else "No")
    print("Yes" if "JON" in data_lookup else "No")
    

    Resulting in:

    Yes
    No
    

    Use the set() version if you don’t care about the rest of the data related to that name or the dict() version if you do. Note that duplicate names will result in some data loss, but if you just want a Yes/No then this should get you going.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search