2017-08-03 57 views
0

已經提出了類似的問題,但沒有一個非常喜歡這個。用Python在文本文件中存儲數據

我需要在文本文件中保存2條信息,用戶名和它們相關的健康整數。現在我需要能夠查看文件並查看用戶,然後查看與之相關的值。在我第一次使用open('text.txt','a')將新用戶和整數附加到txt文件的末尾時編寫它。

我的主要問題是,如何找出哪個值連接到用戶字符串?如果他們在同一條線上,我可以做一些事情,比如只讀那行中的數字?

你們的建議是什麼?如果這些都不起作用,我想我需要轉移到json。

回答

0

This可能是你在找什麼。我建議一次讀一行來解析文本文件。

另一種方法是讀取整個txt並使用類似text_data.split("\n")的字符串來分隔字符串,如果數據按行分隔(用'\ n'表示),該字符串應該可以工作。

1

這將有助於展示您的數據在文件中的外觀以及您可能採用的解決方案的示例。您的文件中是否存在您要添加的分隔符?

0

您可能正在尋找專爲此設計的configparser

構建一個新的配置

>>> 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 
... 

現在讀回

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

檢查的書面文件

% cat example.cfg 
[Players] 
ti7 = 999 
example = 50 
0

如果你已經在各行書面形式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 

注意,這將使得用戶的健康text.txt列出的最後一個值,如果它多次出現,這可能是你想要的,如果你總是附加到文件

% cat text.txt 
user1 100 
user2 150 
user1 200 

上述解析text.txt

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