-1

I'm new to Python and this may sound basic but I have 2 files/class, task1.py and task2.py. I would like to access task1.py functions and data onto task2.py. In other words, whatever printed out that has been printed out by task1.py, I would like to take that output and make use of it, and in this case what I'm doing with that output is exporting it to a CSV file.

This is what my task1.py looks like:

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

And this is what my task2.py looks like:

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'])])

My JSON file for reference:

{  
   "user1":{  
      "Country":[  
         "China",
         "USA",
         "Nepal"
      ],
      "Name":[  
         "Lisbon"
      ]
   },
   "user2":{  
      "Country":[  
         "Sweden",
         "China",
         "USA"
      ],
      "Name":[  
         "Jade"
      ]
   },
   "user3":{  
      "Country":[  
         "India",
         "China",
         "USA"
      ],
      "Name":[  
         "John"
      ]
   }
}
kraljevocs
  • 115
  • 1
  • 2
  • 12
  • 1
    You haven't said what's wrong with your existing code – roganjosh Feb 05 '19 at 09:09
  • Your example code doesn't run, but from what I understand, what you want to do is called "importing functions from other modules" – pj.dewitte Feb 05 '19 at 09:18
  • @pj.dewitte Yes that's what I want to do and I dont know where to start, those two code blocks is originally under 1 file, I would like to separate them – kraljevocs Feb 05 '19 at 09:23
  • @roganjosh refer to my pj.dewitte reply! – kraljevocs Feb 05 '19 at 09:25
  • Please fix your code indentation - it's broken (I mean: without proper indentation, your CODE is broken - it doesn't even compile) – bruno desthuilliers Feb 05 '19 at 10:21
  • @brunodesthuilliers yup it looks broken here but it works fine on my IDE, no worries – kraljevocs Feb 05 '19 at 10:24
  • @kraljevocs you don't understand. We don't care if works in your IDE, what we care about is that WE can NOT understand your code - if the compiler cannot make sense of it, we cannot either, plain and simple. Fo an example, looking at you code, I cannot tell where the `matchCountry` function ends. – bruno desthuilliers Feb 05 '19 at 10:38
  • @brunodesthuilliers Oh yes yes that too, my bad, I've edited it but there's no need for a -2 vote on my question, whoever did that lol – kraljevocs Feb 05 '19 at 10:48
  • @kraljevocs I retracted my downvote since you fixed your snippet, but be sure that python questions with badly indented code are almost systematically downvoted. – bruno desthuilliers Feb 05 '19 at 10:55
  • @brunodesthuilliers Noted – kraljevocs Feb 05 '19 at 11:06

1 Answers1

1

First thing you are referring the function variables in other function which won't work e.g. data and userName.

If you want to use function/class from another python file you can import it and call it for more info on importing see this thread also see below examples:

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'])])
kraljevocs
  • 115
  • 1
  • 2
  • 12
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
  • Thank you for your help, so since in task2.py since my userName variable is still empty, I have to import task1.py function in task2.py? Cuz as of now, the code doesnt work and gives this error--- NameError: global name 'f' is not defined and also my userName is not defined – kraljevocs Feb 05 '19 at 09:54
  • Why you are passing f to the csv.writer `csvwriter = csv.writer(csvfile, f, lineterminator='\n')` ? . You can pass userName variable to exportCSV function similar to `data` – Amit Nanaware Feb 05 '19 at 09:57
  • when I did this "from function2 import matchCountry", it gives me an error ImportError: cannot import name matchCountry. – kraljevocs Feb 05 '19 at 10:02
  • Why you need matchCountry in task2.py? – Amit Nanaware Feb 05 '19 at 10:03
  • Because I would like to call task2.py to export data results from task1.py to CSV file – kraljevocs Feb 05 '19 at 10:04
  • In my answer this is already done by importing task2.py in task1.py and calling `exportCSV(data)` – Amit Nanaware Feb 05 '19 at 10:06
  • But I got an error while calling exportCSV(data), if any(x in data[id]['Acceptable_country'] for x in v['Acceptable_country']): KeyError: – kraljevocs Feb 05 '19 at 10:12
  • check the updated answer above... I think you need to take some python tutorials – Amit Nanaware Feb 05 '19 at 10:14
  • Thank you for the help and yes I just started learning Python, pardon me, and also I'm pretty sure userName is the problem since its not defined in task2.py – kraljevocs Feb 05 '19 at 10:19
  • So you need to pass that to the export function e.g. `def exportCSV(data, id, userName)` check the updated answer – Amit Nanaware Feb 05 '19 at 10:20
  • OH I FIGURED IT OUT! I just had to do the same concept as passing data and id! Thank you for the help! – kraljevocs Feb 05 '19 at 10:22
  • Oh wait you just posted it too – kraljevocs Feb 05 '19 at 10:23