简体   繁体   English

Python CSV导入在Django中不起作用

[英]Python CSV import not working in django

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: 得到了这个load_data.py文件,将csv数据导入到django模型表中...但是它不起作用,在终端中,当我执行命令“ python3 ./load_data.py”时,它就像在load.py一样进入同一行甚至没有这样称呼:

(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 : 这是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")

Any ideas ? 有任何想法吗 ? thanks for your help !! 谢谢你的帮助 !!

You need at the bottom of your code write: 您需要在代码底部编写:

if __name__ == "__main__":
    load_suppliers()

Check this stackoverflow question to learn more about this. 查看此stackoverflow问题以了解更多信息。

Also quoting from python doc : 还引用了python doc

' main ' is the name of the scope in which top-level code executes. main ”是执行顶级代码的范围的名称。 A module's name is set equal to ' main ' when read from standard input, a script, or from an interactive prompt. 从标准输入,脚本或交互式提示中读取时,模块的名称设置为等于“ main ”。

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: 模块可以通过检查其自身的名称来发现其是否在主作用域中运行,这允许使用通用习语在模块中以脚本或python -m方式运行时有条件地执行模块中的代码,而在导入时则不能:

csv_file = base_csv_filepath + "/supplier_data.csv"

添加了/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM