Raghul
Raghul

Reputation: 57

How to check if a file is closed?

Please help me with a code that checks if a file is opened and closes it. I tried the code below and it is not working. I just need python to check if the chat.xls file is opened and if true, python should close chat.xls Kindly help this is what I tried

closeXl = r"C:\Users\R\Downloads\Chat.xls"
if not closeXl.closed:
    closeXl.close()

AttributeError: 'str' object has no attribute 'closed'

Upvotes: 0

Views: 5204

Answers (3)

Hansraj Das
Hansraj Das

Reputation: 239

You should open file before accessing closed attribute

>>> f = open('1.txt')
>>> f
<open file '1.txt', mode 'r' at 0x10de8c6f0>
>>> f.closed
False
>>> f.close()
>>> f.closed
True

Upvotes: 1

Frank
Frank

Reputation: 2029

Your AttributeError seems to say that you should execute .close() on the file handle instead oft the path string.

closeXl = r"C:\Users\R\Downloads\Chat.xls"
file = open(closeX1)

if not file.closed:
    file.close()

In most cases it would be a better solution would be to use the with-statement. It closes the file automatically at the end of the block.

closeXl = r"C:\Users\R\Downloads\Chat.xls"
with open(closeX1) as file:
   pass  # your code here

If you want to check if a file is opened read-write from another process and therefore locked, you should have a look at: https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/

Upvotes: 1

stephen
stephen

Reputation: 115

file_object.closed only works for files that have been opened by the same Python process. At some point you should have done f = open(r"C:\Users\R\Downloads\Chat.xls") (if you haven't, .closed shouldn't work). Then later you can check if not f.closed:.

Upvotes: 0

Related Questions