利用Python中另一个类的函数和数据

时间:2019-02-05 09:07:30

标签: python json python-2.7

我是Python的新手,这听起来很基础,但是我有2个文件/类,task1.py和task2.py。我想访问task1.py函数和数据到task2.py上。换句话说,无论task1.py已打印出什么内容,我都希望使用该输出并加以利用,在这种情况下,我要对该输出执行的操作是将其导出到CSV文件。

这是我task1.py的样子:

def matchCountry():
    userName = raw_input("Enter user's name: ")
    with open('listOfUsers.json') as f:
        data = json.load(f)


    def getId(name):
        for userId, v in data.items():
            if v['Name'][0].lower() == name:
                return userId;
    id = getId(userName)
    for k, v in data.items():
        if any(x in data[id]['Country'] for x in v['Country']):
            if v['Name'][0].lower() != userName.lower():
                result = (v['Name'][0] + " : " + ", ".join(v['Country']))
                print result

这是我的task2.py的样子:

def exportCSV():
    with open('output.csv', 'w') as csvfile:
        csvwriter = csv.writer(csvfile, f, lineterminator='\n')
        csvwriter.writerow(["Name", "Country"])

        for k, v in data.items():
            if any(x in data[id]['Country'] for x in v['Country']):
                if v['Name'][0].lower() != userName.lower():
                    csvwriter.writerow([v['Name'][0], ", ".join(v['Country'])])

我的JSON文件供参考:

{  
   "user1":{  
      "Country":[  
         "China",
         "USA",
         "Nepal"
      ],
      "Name":[  
         "Lisbon"
      ]
   },
   "user2":{  
      "Country":[  
         "Sweden",
         "China",
         "USA"
      ],
      "Name":[  
         "Jade"
      ]
   },
   "user3":{  
      "Country":[  
         "India",
         "China",
         "USA"
      ],
      "Name":[  
         "John"
      ]
   }
}

1 个答案:

答案 0 :(得分:1)

首先,您要在其他函数中引用函数变量,例如,数据和用户名。

如果您想从另一个python文件中使用函数/类,则可以将其导入并调用以获取有关导入的更多信息,请参见thread并参见以下示例:

task1.py

from task2 import exportCSV
userName = raw_input("Enter user's name: ")

def matchCountry():
    with open('listOfUsers.json') as f:
        data = json.load(f)
        return data


def getId(name):
    for userId, v in data.items():
        if v['Name'][0].lower() == name:
            return userId;
data = matchCountry()
id = getId(userName)
for k, v in data.items():
    if any(x in data[id]['Country'] for x in v['Country']):
        if v['Name'][0].lower() != userName.lower():
            result = (v['Name'][0] + " : " + ", ".join(v['Country']))
            print result

exportCSV(data, id, userName)

task2.py:

def exportCSV(data, id, userName):
    with open('output.csv', 'w') as csvfile:
        csvwriter = csv.writer(csvfile, f, lineterminator='\n')
        csvwriter.writerow(["Name", "Country"])

        for k, v in data.items():
            if any(x in data[id]['Country'] for x in v['Country']):
                if v['Name'][0].lower() != userName.lower():
                    csvwriter.writerow([v['Name'][0], ", ".join(v['Country'])])