Python删除临时文件报错--仍在使用

标签 python temporary-files

所以,我通过在 python 中备份一些谷歌文档来创建一堆临时文件。我已经制作了这些文件 os.copy 的适当副本。现在我准备删除它们。我是这样创建它们的:

    line = entry.id.text
title = entry.title.text
splitLine = line.split('/')
key = splitLine[-1]

backUpDir = R'\\XXX\XXXXX\XXXX\XXXXX\otherFiles\GoogleDocBackUp' + '\\'


today = datetime.date.today()
if not os.path.exists(backUpDir + str(today)):
  os.mkdir(backUpDir + str(today))

backupDir = backUpDir + str(today)

tempfile.tempdir = backupDir
file_path = tempfile.mkstemp(suffix='.xls')    

uri = 'http://docs.google.com/feeds/documents/private/full/%s' % key

spreadsheets_client = gdata.spreadsheet.service.SpreadsheetsService()
spreadsheets_client.email = self.gd_client.email
spreadsheets_client.password = self.gd_client.password
spreadsheets_client.source = "My Fancy Spreadsheet Downloader"
spreadsheets_client.ProgrammaticLogin()


# ...
docEntry = self.gd_client.GetDocumentListEntry(uri)

docs_auth_token = self.gd_client.GetClientLoginToken()
self.gd_client.SetClientLoginToken(spreadsheets_client.GetClientLoginToken())
self.gd_client.Export(docEntry, file_path[1])
shutil.copy(file_path[1], backupDir + '//' + title + '.xls')

self.gd_client.SetClientLoginToken(docs_auth_token)  

os.close(file_path[0])

我曾考虑创建一个 tempfile.Temporary 文件而不是 mkstemp,但我遇到了权限错误。 (我怀疑临时文件也试图删除我给它的目录)

回到问题的核心。我尝试对这些临时文件使用 os.remove,python 不会放弃对它的控制。 (我知道我的 os.remove 代码有效,因为我在一些剩余的临时文件上运行了该函数并且它们被毫无问题地删除了。)

我会喜欢这里的一些——如果我可以删除临时文件——太好了。如果我不能,是否可以在 python 中重命名文件?

到目前为止,我得到了一些关于获取 mkstemp 应该返回的文件句柄的建议……但我没有任何运气。当我在调试器中查看它时,我只看到一个整数和文件路径。

更新!我想我修复了它:我只需要在文件路径 [0] 上调用 os.close 并且它看起来像关闭了!谢谢大家!这是更新后的代码

再次感谢。

最佳答案

抱歉,如果这是显而易见的事情,但请检查一下,您是否正在关闭文件,然后再尝试删除它们?

mkstemp()

"returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order"

Python doc source for above

所以我会在尝试删除文件句柄之前尝试调用 close()

关于Python删除临时文件报错--仍在使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11231283/

相关文章:

python - numpy.cov() 异常 : 'float' object has no attribute 'shape'

python - 将 svg 保存到临时文件 Python

java - 如何从 servlet 在/tmp 中创建一个临时文件?

python - 如何重写此代码以列表理解

asp.net - 请建议一种在 Windows Azure 中存储临时文件的方法

python - 无法成功将 stdout 从 Popen 重定向到临时文件

python - 如何使用 io 在内存中生成数据流作为文件之类的对象?

python - NodeJS 与 Express 和 python 交互脚本

python - 在 Python (pandas) 中计算可变现金流 IRR

python - 计算位功能