Reputation: 346
I am trying to check if a file exists, if it does exist, I want to check if it is open by trying to rename it. The except block is trying to close the open file using os.close. When I try to close the file I get "TypeError: an integer is required".
import os
filepath = "C:\Users\oneilp6\Desktop"
file1 = filepath + "\\HelpFile.docx"
file2 = filepath + "\\HelpFile2.docx"
if os.path.exists(file1):
try:
os.rename(file1,file2)
except:
os.close(file1)
Anyone have any thoughts or ideas? I am trying to close a word document that is actually open in MS Word. Is there a way to do that?
Upvotes: 1
Views: 2151
Reputation: 77397
You are checking whether the file is open by a different application on your computer. If it is, there isn't much this program can do about it. You don't get to close other program's files. You could potentially hunt down that program and kill it, but even that isn't easy. There are some suggestions at https://serverfault.com/questions/1966/how-do-you-find-what-process-is-holding-a-file-open-in-windows.
Upvotes: 2
Reputation: 888
There is no file opened in the except
. so no need to call os.close().
https://docs.python.org/2/library/os.html#os.rename
os.close() This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To close a “file object” returned by the built-in function open() or by popen() or fdopen(), use its close() method.
Upvotes: 0