简体   繁体   English

无法访问使用 tempfile 创建的临时文件

[英]Can't access temporary files created with tempfile

I am using tempfile.NamedTemporaryFile() to store some text until the program ends.我正在使用tempfile.NamedTemporaryFile()来存储一些文本,直到程序结束。 On Unix is working without any issues but on Windows the file returned isn't accessible for reading or writing: python gives Errno 13. The only way is to set delete=False and manually delete the file with os.remove() .在 Unix 上工作没有任何问题,但在 Windows 上,无法读取或写入返回的文件:python 提供 Errno 13。唯一的方法是设置delete=False并使用os.remove()手动删除文件。 Why?为什么?

This causes the IOError because the file can be opened only once after it is created. 这将导致IOError,因为文件创建后只能打开一次。

The reason is because NamedTemporaryFile creates the file with FILE_SHARE_DELETE flag on Windows. 原因是因为NamedTemporaryFile在Windows上创建带有FILE_SHARE_DELETE标志的文件。 On Windows when a file has been created/opened with specific share flag all subsequent open operations have to pass this share flag. 在Windows上,当使用特定共享标记创建/打开文件时,所有后续打开操作都必须通过此共享标记。 It's not the case with Python's open function which does not pass FILE_SHARE_DELETE flag. Python的open函数不是通过FILE_SHARE_DELETE标志的情况并非FILE_SHARE_DELETE See my answer on How to create a temporary file that can be read by a subprocess? 请参阅我关于如何创建可由子进程读取的临时文件的答案 question for more details and a workaround. 有关更多详细信息和解决方法的问题。

Take a look: http://docs.python.org/2/library/tempfile.html 看看: http : //docs.python.org/2/library/tempfile.html

 tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). 此函数的操作与TemporaryFile()完全相同,只是保证文件在文件系统中具有可见的名称(在Unix上,目录条目未取消链接)。 That name can be retrieved from the name attribute of the file object. 可以从文件对象的名称属性中检索该名称。 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(默认设置),则在关闭文件后立即将其删除。

Thanks to @Rnhmjoj here is a working solution:感谢@Rnhmjoj,这是一个可行的解决方案:

    file = NamedTemporaryFile(delete=False)
    file.close()

You have to keep the file with the delete -flag and then close it after creation.您必须使用delete -flag 保留文件,然后在创建后将其关闭。 This way, Windows will unlock the file and you can do stuff with it!这样,Windows 将解锁文件,您可以使用它来做事!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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