[英]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. 我使用
tempfile.NamedTemporaryFile()
创建临时文件,并使用一些csv数据将其加载到mysql数据库中。 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
我把
time.sleep(100)
有时间进行manualy检查文件是否存在且该文件是否存在并且有正确的数据(我用我的favit文本编辑器检查),但是当我在MySQL查询中使用这个文件时,我有错误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 看起来程序不等待
cur.execute(sql)
如果我用tempfile.NamedTemporaryFile(delete=False)
创建临时文件tempfile.NamedTemporaryFile(delete=False)
然后我没有错误,但如果我尝试删除文件与os.remove()
后cur.execute(sql)
然后我再次有这个错误
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).
名称是否可以用于第二次打开文件,而命名的临时文件仍然是打开的,因此不同平台(它可以在Unix上使用;它不能在Windows NT或更高版本上使用)。 If delete is true (the default), the file is deleted as soon as it is closed.
如果delete为true(默认值),则文件一关闭就会被删除。
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
. 我对mysql并不过分熟悉,但我想你应该在
f.seek(0)
之后传递文件对象f
而不是尝试使用.name
再次打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.