【问题标题】:peek of closed file error while reading a binary file读取二进制文件时查看已关闭文件错误
【发布时间】:2020-07-22 11:05:17
【问题描述】:

我正在尝试将文件中的一些数据插入 MySQL 数据库。但是,在读取文件时会显示错误。

这是我从文件插入数据库到 MySQL 数据库的代码:

import mysql.connector
import pickle
try:
    connection = mysql.connector.connect(host='localhost',
                                         database='PETROL',
                                         user='Sarthak',
                                         password='q1w2e3r4t5')
    cursor = connection.cursor ( )
    print(connection)
    fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
    pv=[]
    while True :
        try :
            pdate = pickle.load (fp1)
            pv.append(pdate)
        except EOFError :
            for i in pv:
                ins = ("INSERT INTO DATES (Date) VALUES (%(i)s)")
                data ={'i' : i}
                cursor.execute(ins,data)
            fp1.close ()
        connection.commit()
except mysql.connector.Error as error:
    print("Failed to create table in MySQL: {}".format(error))
    cursor.close()
    connection.close()

弹出这种错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "D:\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/sarth/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch.py", line 14, in <module>
    pdate = pickle.load (fp1)
ValueError: peek of closed file

【问题讨论】:

    标签: python pickle file-handling


    【解决方案1】:

    由于您没有退出While 循环,并且在处理EOFErrorfp1 指针已经关闭,因此您会收到此错误。

    解决此问题的一种方法是在遇到EOFError 时将break 移出while 循环。

    所以代码变成了:

    except EOFError :
                for i in pv:
                    ins = ("INSERT INTO DATES (Date) VALUES (%(i)s)")
                    data ={'i' : i}
                    cursor.execute(ins,data)
                fp1.close ()
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 2012-11-26
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多