I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is?
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.
In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.
There is no way in python natively to track all opened files. To do that you should either track all the files yourself or always use the with statement to open files which automatically closes the file as it goes out of scope or encounters an error.
To list all open files in a cross-platform manner, I would recommend psutil.
#!/usr/bin/env python import psutil for proc in psutil.process_iter(): print(proc.open_files())
The original question implicitly restricts the operation to the currently running process, which can be accessed through psutil's Process class.
proc = psutil.Process() print(proc.open_files())
Lastly, you'll want to run the code using an account with the appropriate permissions to access this information or you may see AccessDenied errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With