读取二进制文件时查看关闭文件错误

peek of closed file error while reading a binary file

我正在尝试将文件中的一些数据插入到 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

因为你没有跳出While循环,而且fp1指针在处理EOFError的时候已经关闭了,你得到这个错误。

解决此问题的一种方法是在遇到 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