OpenSrcFTW
OpenSrcFTW

Reputation: 211

os.rename() fails, in use by another process

So I'm trying to rename a file, and it keeps saying "The process cannot access the file because it is being used by another process." But I know it's not being used by another process so I'm not sure what's going on. Here's my code

while self.fileSet.hasMoreFiles():
    file = self.fileSet.nextFile()
    periodIndex=file.find(".")
    extension = file[periodIndex:]
    baseName=file[:periodIndex]
    self.newFile=open(file, 'w+')
    self.backupName = baseName + "_bak" + extension
    os.rename(file, baseName + "_bak" + extension)
    self.newFile=open(file, 'w+')
    self.writeNew()

Upvotes: 4

Views: 6042

Answers (1)

Amber
Amber

Reputation: 526573

You open the file 2 lines before you try to call os.rename on it, but you don't close it before trying to rename it, so your own program still has it open.

Call self.newFile.close() before the os.rename() and you should avoid that error - or better yet, don't call open() at all before the rename, given that you're not actually using the opened file (and you open it right after the rename anyway).


Some tangential notes:

  • You shouldn't name a variable file - there's already a type named file that you're shadowing if you do that.

  • You duplicate a lot of code - for instance, you just created self.backupName on the line above the rename, but then you re-calculate it. Why not just pass self.backupName as the second argument to os.rename()?

  • You can skip the find call and subsequent slicing by using os.path.splitext().

All in all, you could condense your code down to this:

while self.fileSet.hasMoreFiles():
    curFile = self.fileSet.nextFile()
    baseName, extension = os.path.splitext(curFile)
    self.backupName = baseName + "_bak" + extension
    os.rename(curFile, self.backupName)
    self.newFile = open(curFile, 'w+')
    self.writeNew()

Upvotes: 7

Related Questions