0

Similar questions have been asked but none quite like this.

I need to save 2 pieces of information in a text file, the username and their associated health integer. Now I need to be able to look into the file and see the user and then see what value is connected with it. Writing it the first time I plan to use open('text.txt', 'a') to append the new user and integers to the end of the txt file.

my main problem is this, How do I figure out which value is connected to a user string? If they're on the same line can I do something like read the only the number in that line?

What are your guys' suggestions? If none of this works, I guess I'll need to move over to json.

Colwin
  • 2,655
  • 3
  • 25
  • 25
jumbodrawn
  • 128
  • 1
  • 9

3 Answers3

0

This may be what you're looking for. I'd suggest reading one line at a time to parse through the text file.

Another method would be to read the entire txt and separate strings using something like text_data.split("\n"), which should work if the data is separated by line (denoted by '\n').

Landmaster
  • 1,043
  • 2
  • 13
  • 21
0

You're probably looking for configparser which is designed for just that!

Construct a new configuration

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config['Players'] = {
...     "ti7": 999,
...     "example": 50
... }
>>> with open('example.cfg', 'w') as fh:
...     config.write(fh)  # write directly to file handler
...

Now read it back

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read("example.cfg")
['example.cfg']
>>> print(dict(config["Players"]))
{'ti7': '999', 'example': '50'}

Inspecting the written file

% cat example.cfg
[Players]
ti7 = 999
example = 50
ti7
  • 16,375
  • 6
  • 40
  • 68
0

If you already have a text config written in the form key value in each line, you can probably parse your config file as follows:

user_healths = {}                              # start empty dictionary
with open("text.txt", 'r') as fh:              # open file for reading
    for line in fh.read().strip().split('\n'): # list lines, ignore last empty
        user, health = line.split(maxsplit=1)  # "a b c" -> ["a", "b c"]
        user_healths[user] = int(health)       # ValueError if not number

Note that this will make the user's health the last value listed in text.txt if it appears multiple times, which may be what you want if you always append to the file

% cat text.txt
user1 100
user2 150
user1 200

Parsing text.txt above:

>>> print(user_healths)
{'user1': 200, 'user2': 150}
ti7
  • 16,375
  • 6
  • 40
  • 68