从JSON文件中检索响应

时间:2016-09-27 16:34:30

标签: python json

我试图从JSON文件中提取一些值,但它似乎并没有起作用。此外,当我尝试添加打印语句以查看它在哪里时,没有任何打印。任何人都可以看到为什么这不起作用的明显原因?我唯一能想到的是它与我最近从PC切换到Mac的事实有关,文件存储为rtf而不是txt。

import glob2
import json

fdr = glob2.glob('/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/*.rtf')    #insert all rtf files in folder into list

for dr in fdr:        #loop through file list
    print(dr)
    ending = str(dr[57:])     #cut filename from pathname
    pe = ending.replace('.rtf', '')    #add filename to path
    f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv'     #format the file as csv
    f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe            #access rtf file
    print(f_n)

    file_path = 'f_n'
    file_out = 'f_quest'
    with open(file_path) as f_in, open(file_out) as f_out:
        data = json.load(f_in)
    print(data.keys())  # list the dicts keys

    q = 'vviq'
    response = data[q]['response']
    f_out.write('response')    #write responses to new .csv file

1 个答案:

答案 0 :(得分:1)

您的代码没有输出任何内容,因为您在python脚本的目录中创建并打开一个名为f_n的空文件,然后尝试使用json模块加载它。

这些是分配给字符串文字的变量,而不是您之前定义的变量。

file_path = 'f_n'
file_out = 'f_quest'

这些变量分配给系统上的路径

f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv'     #format the file as csv
f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe            #access rtf file

我认为你想要打开后者?如果是这种情况,那么前面的变量就完全没有意义了。您应该将这些变量赋予open(),但不要引用变量名称。

此外,open()默认为读取模式,因此当您尝试执行f_out.write('response')时,可能需要修复此问题,with应该在'response'之下,否则文件已关闭,再次response是“响应”一词的字符串文字,而不是您在上一行中指定的radius变量