1

So this is my text file

player_basic, [10, 1, "SCISSOR", True]
Enemy3, [10, 1, "SCISSOR", True]
Enemy2, [10, 1, "PAPER", True]
Enemy1, [10, 1, "ROCK", True]

My code creates a list of the lines in the file (minus the first line), but only in one string per line. I can't figure out a way to change each line into a tuple with different types in it.

num_enemys = 0

def initialize_enemy(num_enemys):
    data_list = []
    data = open("test.txt", "r")
    raw_data_list = data.readlines()
    for line in raw_data_list:
        line.replace('\'', '')
        data_list.append(line)
    data.close()
    data_list.pop(0)
    return data_list[num_enemys:]

Any help would be great thanks

Guec
  • 13
  • 2
  • see how to write a tuple to a file: https://stackoverflow.com/questions/8366276/writing-a-list-of-tuples-to-a-text-file-in-python – Golden Lion Feb 13 '21 at 18:02
  • Don't make up your own file format. Use something for which a parser already exists: CSV, JSON, YAML, etc. – chepner Feb 13 '21 at 21:35

1 Answers1

0

Is this what you wanted?

num_enemys = 0
def initialize_enemy(num_enemys):
  data_list = []
  data = open("test.txt", "r")
  raw_data_list = data.readlines()
  for line in raw_data_list:
    line = line.replace('\'','').replace('[', '').replace(']','').replace('"','')
    lis = []
    for ele in line.split(',')[1:]:
        if ele.strip().isdigit():
            lis.append(int(ele.strip()))
        elif ele.strip() in ['True','False']:
            lis.append(bool(ele.strip()))
        else:
            lis.append(ele.strip())
    data_list.append((line.split()[0].strip(','),lis))
    data.close()
    data_list.pop(0)
    return data_list[num_enemys:]

Output:

[('Enemy3', [10, 1, 'SCISSOR', True]), ('Enemy2', [10, 1, 'PAPER', True]), ('Enemy1', [10, 1, 'ROCK', True])]
SURYA TEJA
  • 204
  • 3
  • 8