Search code examples
pythontemporary-files

Python Delete temporary file error--Still in use


So, I am creating a bunch of temporary files from backing up some google docs in python. I have already made the appropriate copies of these files os.copy. Now I am ready to delete them. I created them like this:

    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])

I had looked at creating a tempfile.Temporary file instead of the mkstemp, but I was getting permissions errors. (I suspect that the temporary file tried to delete the directory that I gave it as well)

So back to the meat of the problem. I try to use os.remove on these temporary files and python will not relinquish its hold on it. (I know that my os.remove code works because I ran that function on some of the left over temporary files and they were deleted without problems.)

I would love some here--If I can delete the temporary files--great. If I can't, is there anyway to rename a file in place in python?

So far, I've gotten some suggestions about grabbing the file handle that the mkstemp SHOULD return...but I am not having any luck. When I look at it in the debugger, I only see an integer and the file path.

UPDATE! I think I fixed it: I just had to call os.close on filepath[0] and it looks like it closed! Thanks everyone! Here is the updated code

Thanks again.


Solution

  • Sorry if this is something obvious, but just checking, you are closing the files when you are done with them before trying to delete them right?

    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

    So I would try the close() call on your file handle before trying to delete it.