简体   繁体   中英

How do I open (twice) file created with tempfile.NamedTemporaryFile()

I create temporary file using tempfile.NamedTemporaryFile() with some csv data to load it into mysql database. I put time.sleep(100) to have time for manualy check if file exist and this file exist and have proper data (I check it with my favorit text editor), but when I use this file in MySQL query then I have error file not found

db = MyDBConnect()
cur = db.cursor()
csvfile = tempfile.NamedTemporaryFile()
with csvfile as f:
    f.write("\n".join(results).encode('utf-8'))
    sql = "LOAD DATA LOCAL INFILE '" + csvfile.name + "' INTO TABLE MyResults FIELDS TERMINATED BY ','"
    cur.execute(sql)
    time.sleep(100)​

full error message:

Exception _mysql_exceptions.InternalError: (2, "File '/tmp/tmpQtHxe6' not found (Errcode: 2)") in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x7f9e3fcef4d0>> ignored​

I found something strange for me. It's looks like program doesn't wait for cur.execute(sql) if I create temp file with tempfile.NamedTemporaryFile(delete=False) then I have no error, but If I try delete file with os.remove() after cur.execute(sql) then I again have this error

From the docs :

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed.

I am not overly familiar with mysql but I imagine you should maybe be passing the file object f after a f.seek(0) not trying to open again using .name .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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