2016-01-14 92 views
-1

得到這個load_data.py文件導入一個CSV數據到Django模型表...但它不工作,在終端,因爲我執行命令「python3 ./load_data.py」它只是轉到同一行,如果load.py甚至不叫這樣的:Python的CSV導入不工作在Django

(cost_control_local) [email protected]:~/cost_control_repository/cost_control/csv_data$ python3 ./load_data.py 
(cost_control_local) [email protected]:~/cost_control_repository/cost_control/csv_data$ 

這是load_data.py代碼:

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") 

任何想法?謝謝你的幫助 !!

回答

1

你需要在你的代碼寫的底部:

if __name__ == "__main__": 
    load_suppliers() 

檢查這個stackoverflow question更多地瞭解這一點。

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:

+0

拋出我這個錯誤:ValueError異常:無效的字面INT()基數爲10: '\ ufeffID' – jsanchezs

+1

那麼這就是您的腳本錯誤。您需要展示完整的回溯信息以供人們診斷您的錯誤,但我們無法通過「ValueError」確定哪些問題。此外,由於您的程序已開始運行,因此與該問題無關,因此我建議您關閉此問題並提出另一個問題,以便讓更多人受益。 –

1
csv_file = base_csv_filepath + "/supplier_data.csv" 

添加了/