-1

Got this load_data.py file to import a csv data to a django model table...but it's not working, in terminal as i execute command "python3 ./load_data.py" it just goes to the same line as if load.py weren't even called like this:

(cost_control_local) juanda@juanda-VirtualBox:~/cost_control_repository/cost_control/csv_data$ python3 ./load_data.py
(cost_control_local) juanda@juanda-VirtualBox:~/cost_control_repository/cost_control/csv_data$ 

this is the load_data.py code :

import csv,sys,os
import django

pathproject = "/home/juanda/cost_control_repository/cost_control"
base_csv_filepath = "/home/juanda/cost_control_repository/cost_control/csv_data"
sys.path.append(pathproject)
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings.local'
django.setup()

from cost_control_app.models import Suppliers

def load_suppliers():
    print ("Entering...")
    csv_file = base_csv_filepath + "supplier_data.csv"
    dataReader = csv.reader(open(csv_file, encoding='utf-8'),delimiter=',',quotechar='"')
    #dataReader = csv.reader(open(csv_file), delimiter=',', quotechar='"')
    for row in dataReader:
        if row[0] != 'ID':
            Suppliers.objects.create(
                supplier=row[0],
                supplier_description=row[1]
            )
    print ("Imported correctly")

Any ideas ? thanks for your help !!

jsanchezs
  • 1,992
  • 3
  • 25
  • 51

2 Answers2

1

You need at the bottom of your code write:

if __name__ == "__main__":
    load_suppliers()

Check this stackoverflow question to learn more about this.

Also quoting from python doc:

'main' is the name of the scope in which top-level code executes. A module’s name is set equal to 'main' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

Community
  • 1
  • 1
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Throws me this error : ValueError: invalid literal for int() with base 10: '\ufeffID' – jsanchezs Jan 14 '16 at 20:02
  • 1
    Then that's the error in your script. You need to show the full traceback for people to diagnose your error, we couldn't determine what's wrong by just "ValueError". Also, it's not related to this question anymore because your program starts to run, so I suggest you close this one and ask another question so more people might benefit from it. – Shang Wang Jan 14 '16 at 20:05
1
csv_file = base_csv_filepath + "/supplier_data.csv"

Added the /

Loïc
  • 11,804
  • 1
  • 31
  • 49