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

标签 python json string find

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

    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

关于python - 如何在 Python 中使用 JSON 从文件的特定列表中检索特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18391165/

相关文章:

python - 如何使用函数中的参数来定义要在函数中使用的数据框的名称?

java - 如何将 JSONArray 转换为 int 数组?

php - string - PHP 中的数组歧义

C# '\n' 保存在与预期不同的字节中

python - 如何上传图片并在 Google Cloud Bucket 中公开

python - Django 中的 ViewDoesNotExist

python - BigQuery Python API : Preserve null fields during extract_table job

java - RESTful 放置 id 和 body

javascript - .json()用于错误处理的内容是什么?

string - 在 Swift 单元测试中比较字符串