简体   繁体   English

使用Python在文本文件中存储数据

[英]Storing Data With Python in Text Files

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. 我需要在文本文件中保存2条信息,用户名及其关联的健康整数。 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. 第一次编写时,我打算使用open('text.txt','a')将新用户和整数附加到txt文件的末尾。

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. 如果这些都不起作用,我想我需要移到json。

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'). 另一种方法是使用诸如text_data.split("\\n")类的text_data.split("\\n")读取整个txt并分离字符串,如果数据以行分隔(以'\\ n'表示text_data.split("\\n") ,则该方法应该有效。

You're probably looking for configparser which is designed for just that! 您可能正在寻找为此而设计的configparser

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

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: 如果您已经在每一行中以表单key value编写了文本配置,则可以按以下方式解析配置文件:

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 请注意,如果多次出现,这将使用户的健康状况成为text.txt列出的最后一个值,如果您始终附加到文件,则可能是您想要的值

% cat text.txt
user1 100
user2 150
user1 200

Parsing text.txt above: 解析上面的text.txt

>>> print(user_healths)
{'user1': 200, 'user2': 150}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM