0

I have a plain text file with some data in it, that I'm trying to open and read using a Python (ver 3.2) program, and trying to load that data into a data structure within the program.

Here's what my text file looks like (file is called "data.txt")

NAME: Joe Smith
CLASS: Fighter
STR: 14
DEX: 7

Here's what my program looks like:

player_name = None
player_class = None
player_STR = None
player_DEX = None
f = open("data.txt")
data = f.readlines()
for d in data:
    # parse input, assign values to variables
    print(d)
f.close()

My question is, how do I assign the values to the variables (something like setting player_STR = 14 within the program)?

3 Answers 3

2
player = {}
f = open("data.txt")
data = f.readlines()
for line in data:
    # parse input, assign values to variables
    key, value = line.split(":")
    player[key.strip()] = value.strip()
f.close()

now the name of your player will be player['name'], and the same goes for all other properties in your file.

Sign up to request clarification or add additional context in comments.

Comments

1
import re

pattern = re.compile(r'([\w]+): ([\w\s]+)')

f = open("data.txt")
v = dict(pattern.findall(f.read()))
player_name = v.get("name")
plater_class = v.get('class')
# ...


f.close()

2 Comments

Why go through the hussle of searching the entire file with a regex, if you know the format of the file will be a key:value pair on every line?
Did you run this code? It founds nothing. Because "NAME: Joe Smith" != "name: Joe Smith"
0

The most direct way to do it is to assign the variables one at a time:

f = open("data.txt")              
for line in f:                       # loop over the file directly
    line = line.rstrip()             # remove the trailing newline
    if line.startswith('NAME: '):
        player_name = line[6:]
    elif line.startswith('CLASS: '):
        player_class = line[7:]
    elif line.startswith('STR: '):
        player_strength = int(line[5:])
    elif line.startswith('DEX: '):
        player_dexterity = int(line[5:])
    else:
        raise ValueError('Unknown attribute: %r' % line)
f.close()

That said, most Python programmers would stored the values in a dictionary rather than in variables. The fields can be stripped (removing the line endings) and split with: characteristic, value = data.rstrip().split(':'). If the value should be a number instead of a string, convert it with float() or int().

3 Comments

how about for the sake of performance, assign the fields to the variables already? Something like strip the name, and assign the number/string to the field in object named same as the stripped string. Would that work?
Performance is a red-herring here. The OP's task is IO bound, so the time to read the file dominates the processsing. Also, direct variable assignment uses a dictionary (globals) behind the scences, so there isn't any essential difference between the two approaches.
What if DEX:14 or dex: 14? It would be unknow attr, but is it really unknown?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.