【问题标题】:Python/MySQL - import csv file to mysqlPython/MySQL - 将 csv 文件导入 mysql
【发布时间】:2020-01-14 18:47:39
【问题描述】:

我正在开发一个应用程序,该应用程序包括在目录中选择一个文件 (.csv) 并将其中的数据导入数据库 (mysql),但出现以下错误:

Traceback (most recent call last):
  File "C:\Users\TESTES\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/TESTES/PycharmProjects/Heiken/tess.py", line 16, in import_file
    with open(browse_file):
TypeError: expected str, bytes or os.PathLike object, not function

下面是完整的函数代码,在测试界面中:

from tkinter import *
import pymysql
from tkinter import filedialog

tess = Tk()

def browse_file():

    fname = filedialog.askopenfilename(filetypes=(("Template files", "*.csv"), ("All files", "*")))
    print(fname)

def import_file():
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='omnia')
    print('connect successfull!')

    with open(browse_file):
        statm = "INSERT INTO omniacademp(n_id, n_cod, c_cnpjcpf, c_razao, c_enderecom, c_nr, c_compl, c_cep, c_bairro, c_cidade, c_estado, c_telefone, c_email, c_celular, c_email2) VALUES (0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor = conn.cursor()
        cursor.execute(statm)
        conn.commit()



bt = Button(tess, text='browse file', command=browse_file)
bt.place(x=10, y=10)

bt = Button(tess, text='import file', command=import_file)
bt.place(x=10, y=45)


tess.mainloop()

【问题讨论】:

  • 当您调用cursor.execute() 时,您缺少要填写所有占位符的值列表。你永远不会从文件中读取数据。
  • with open(browse_file): 没有意义。 browse_file 是一个函数,而不是文件名。如果您将browse_file() 更改为return fname,您可以将其更改为with open(browse_file()) as f:,然后从f 读取。

标签: python mysql csv tkinter


【解决方案1】:

首先,您应该从browse_file 函数返回路径。试试这个:

from tkinter import *
import pymysql
from tkinter import filedialog

tess = Tk()

def browse_file():
    return filedialog.askopenfilename(filetypes=(("Template files", "*.csv"), ("All files", "*")))

def import_file():
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='omnia')
    print('connect successfull!')

    with open(browse_file()):
        statm = "INSERT INTO omniacademp(n_id, n_cod, c_cnpjcpf, c_razao, c_enderecom, c_nr, c_compl, c_cep, c_bairro, c_cidade, c_estado, c_telefone, c_email, c_celular, c_email2) VALUES (0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor = conn.cursor()
        cursor.execute(statm)
        conn.commit()



bt = Button(tess, text='browse file', command=browse_file)
bt.place(x=10, y=10)

bt = Button(tess, text='import file', command=import_file)
bt.place(x=10, y=45)


tess.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 2019-09-17
    • 2011-05-07
    相关资源
    最近更新 更多