Skip to main content
 首页 » 编程设计

python之如何在 Python 中使用 JSON 从文件的特定列表中检索特定字符串

2025年05月04日22hnrainll

我得到的代码实际上在同一个列表中保存了三个不同的数据字符串。每个列表都是分开的,我什至不确定这是否有意义...所以我将只粘贴代码:

    filename = "datosdeusuario.txt" 
    leyendo = open(filename, 'r+') 
    buffer = leyendo.read() 
    leyendo.close() 
    if not user.name in buffer: 
      escribiendo = open(filename, 'a') 
      escribiendo.write(json.dumps([user.name, string2, string3])+"\n") 
      escribiendo.close() 
      print(str(horaactual)[:19] + ": Data from " + user.name + " added") 

该代码正在像这样保存信息(并且几乎完美地工作):

["saelyth", "thisisanexampleforstring2", "andthisisanexampleforstring3"] 
["anothername", "thisisanothernexampleforstring2", "andthisisanotherexampleforstring3"] 
["John Connor", "exampleforstring2", "exampleforstring3"] 

所以我的实际问题是...从该文件中获取特定字符串的最佳方法是什么?

例如,假设我只想检索第一个字符串、第二个字符串和第三个字符串如果 user.name 是John Connor(我的意思是,找到名称的列表中的所有三个值)。我似乎无法找到正确的方法来进行谷歌搜索。预期的代码将是这样的:

if user.name is in found in any list(position1) of the file datosdeusuario.txt 
then 
retrieveddata1 = List where value1 is user.name(get value1) 
retrieveddata2 = List where value1 is user.name(get value2) 
retrieveddata3 = List where value1 is user.name(get value3) 

我不知道该怎么做。这就是为什么我只是编写代码来解释这种情况。

请您参考如下方法:

我不确定这是否是您想要的但是:

filename = "datosdeusuario.txt" 
f = open(filename,"r") 
filedata = f.read() 
f.close() 
sp1 = filedata.split("\n") 
a = "" 
for x in sp1: 
    if "joao m" in x: 
        a = x 
if(len(a) > 0): 
    sp2 = a.split('"') 
    values = [] 
    for x in sp2: 
        if not(x == ", " or x == "]" or x == "[" or len(x) == 0): 
            values.append(x) 
    print values[0] #should by the name 
    print values[1] #value 2 
    print values[2] #value 3        
else: #No username in the file 
    #do something 
    pass