提问者:小点点

如何在Python中使用“with open”逻辑定义函数?


我试图定义一个函数,该函数基于从JSON文件接收的数据创建一个有序对列表。 我创建了一个数据文件(“contacts.txt”),并将数据存储在该文件中。 请参阅此处的代码图像:

import json

# Generating false user data for purposes of testing. In production, this code will be modified to read individual JSON objects
# and combine them into one file.
# Assumes mobile application JSON tracks 2 contacts for each user
data = {}
data['contacts'] = []
data['contacts'].append({
    'userID': 'u1',
    'userPSEUDO': 'u1',
    'risk': '37',
    'lc1': 'u2',
    'lc2': 'u3',
})
data['contacts'].append({
    'userID': 'u2',
    'userPSEUDO': 'u2',
    'risk': '18',
    'lc1': 'u1',
    'lc2': 'u3',
})
data['contacts'].append({
    'userID': 'u3',
    'userPSEUDO': 'u3',
    'risk': '83',
    'lc1': 'u2',
    'lc2': 'u1',
})

with open('contacts.txt', 'w') as outfile:
    json.dump(data, outfile)

然后我编写了一个文件,该文件访问“contact.txt”数据,并从该数据生成有序对。 请参阅此处的代码图像:

import json
# Need to define this code as a function
# def tracing_list():
with open('contacts.txt') as json_file:
    data = json.load(json_file)
    for p in data['contacts']:
    # Defining user dictionary to hold contact variables
        UserDict = {}
        A = 'userPSEUDO'
        B = 'lc1'
        C = 'userPSEUDO'
        D = 'lc2'
    # Populating user dictionary
    # This code prints the userPSEUDO as variables A and C and
    # prints the lc1 and lc2 as variables B and D. 
        UserDict[A] = p['userPSEUDO']
        UserDict[B] = p['lc1']
        UserDict[C] = p['userPSEUDO']
        UserDict[D] = p['lc2']
    # Printing contact ordered pairs from dictionary
        print(UserDict[A] + "," + UserDict[B])
        print(UserDict[C] + "," + UserDict[D])  

这段代码为每个“userpseudo”和JSON数据中包含的记录联系人输出一组有序对。 每个“userpseudo”都有两个存储的联系人,带有变量“lc1”和“lc2”。 因此,对于每个不同的“userpseudo”(有三个,定义为“u1,u2和u3”),输出的格式为“userpseudo,lc1”和“userpseudo,lc2”。因此,我们的输出如下所示:(为了清楚起见,我用分隔符将其划分,通常它是一个列表。)

u1,u2 u1,u3 u2,u1 u2,u3 u3,u2 u3,u1

我试图定义一个名为“tracing_list”的函数,它动态输出这个列表,可以根据需要从我的程序的其他部分调用。 我正在遇到这样一个问题,即代码在不定义函数的情况下运行时运行得很完美,但当我定义了函数并正确缩进时,它却不生成任何输出。 它也不会出错,只是不生成列表。 我的函数代码如下:

import json
# Need to define this code as a function
def tracing_list():
    with open('contacts.txt') as json_file:
        data = json.load(json_file)
        for p in data['contacts']:
    # Defining user dictionary to hold contact variables
            UserDict = {}
            A = 'userPSEUDO'
            B = 'lc1'
            C = 'userPSEUDO'
            D = 'lc2'
    # Populating user dictionary
    # This code prints the userPSEUDO as variables A and C and
    # prints the lc1 and lc2 as variables B and D. 
            UserDict[A] = p['userPSEUDO']
            UserDict[B] = p['lc1']
            UserDict[C] = p['userPSEUDO']
            UserDict[D] = p['lc2']
    # Printing contact ordered pairs from dictionary
            print(UserDict[A] + "," + UserDict[B])
            print(UserDict[C] + "," + UserDict[D])

我做错了什么,如何用我已经有的代码定义我的函数?


共1个答案

匿名用户