Be aware that this is very Windows specific as most other OSes will happily rename files if they're already open. You could use with open "path" as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code : try: with open "path", "r" as file: or just open Code here except IOError: raise error or print.
DanielTuzes 1, 15 15 silver badges 33 33 bronze badges. Never do an except without specifying the exception you want to catch. Also, the scope of your try block is too broad - Shansal wants to check whether the file can be opened at all. Error handling while writing to the file or whatever else happens in the with block should be separate. Using try: with open "path", "r" as file: or just open may cause some troubles when file is opened by some other processes i.
EnsureDispatch 'Excel. Workbooks : xl. Just use this function. It will close any already opened excel file import os def close : try: os. Dexter Dexter 5 5 silver badges 13 13 bronze badges. It is basically a copy of this existing answer that uses the. Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name.
Email Required, but never shown. The Overflow Blog. Follow Post Reply. This discussion thread is closed Start new discussion. Similar topics PHP. Reality Check: Session Hijacking. Check the parent windows state from child. Visual Basic. Check is form is disposed.
How to check for a closed socket. Related Articles. Table of Contents. Improve Article. Save Article. Like Article. Last Updated : 24 Feb, Import module. Initializing the wmi constructor. Two types of files can be created to store data. These are text files and binary files. Any file is required to open before reading or write. The open function is used in Python to open a file. Using the open function is one way to check a particular file is opened or closed.
If the open function opens a previously opened file, then an IOError will be generated. Another way to check a file is opened or closed is to check the values of the closed property of the file handler object. Using rename function is another way to check the file is opened or closed. Different ways to check any file is opened or closed in Python have been shown in this tutorial.
0コメント