473,396 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to close all python-opened file identifiers?

Greetings from beautiful Tucson, Arizona.

Question: Is there a way in Python to determine what all file
identifiers have been opened by Python, and to close them all?

Why I ask: I learned Python after cutting my programming teeth on
Matlab, where you get a list of all open file identifiers (that is,
those opened from a particular Matlab session) with "fopen('all')" and
close them with "fclose('all')". In my 4 years of experience with
Python, I haven't yet come across an equivalent means of doing this in
Python. I understand that this problem can be prevented by making
sure a "fid.close()" exists for every "open"; I need this however for
a file-permissions troubleshooting problem.

Extra info on this specific problem: In my program, python (through
subprocess) launched a text editor on a text file, and I can't seem to
save the text file through that editor (I get a "this document is in
use by another application and cannot be accessed" error from the
editor [wordpad on winXp]). The text file in question is modified by
my program prior to its loading into the launched editor. Although I
can't find unmatched "open" and "fid.close()" statements, I'd like to
implement a check for open file identifiers before launching the
editor.

Thanks very much in advance for your time and any help you can provide.
Jul 26 '08 #1
2 10876
BAnderton <bl************@gmail.comwrote:
>
Question: Is there a way in Python to determine what all file
identifiers have been opened by Python, and to close them all?
No. You are expected to be able to track this yourself. Python doesn't
open any files that you didn't request.

>Extra info on this specific problem: In my program, python (through
subprocess) launched a text editor on a text file, and I can't seem to
save the text file through that editor (I get a "this document is in
use by another application and cannot be accessed" error from the
editor [wordpad on winXp]). The text file in question is modified by
my program prior to its loading into the launched editor. Although I
can't find unmatched "open" and "fid.close()" statements, I'd like to
implement a check for open file identifiers before launching the
editor.
If you want to post some code, perhaps we can find something.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 27 '08 #2
On Jul 26, 2:19*am, BAnderton <blake.ander...@gmail.comwrote:
*Although I
can't find unmatched "open" and "fid.close()" statements, I'd like to
implement a check for open file identifiers before launching the
editor.
So you need a debug tool to track down the opened files.
How about that:

# assume Python 2.5
from __future__ import with_statement

import __builtin__

orig_file = __builtin__.file # you could do the same for open

class ChattyFile(file):
opened = []
def __init__(self, *args, **kw):
super(ChattyFile, self).__init__(*args, **kw)
self.opened.append(self)
print 'opened %s' % self
def close(self):
super(ChattyFile, self).close()
self.opened.remove(self)
print 'closed %s' % self

class ContextManager(object):
def __init__(self):
self.opened = ChattyFile.opened
def __enter__(self):
__builtin__.file = ChattyFile
def __exit__(self, *exc_info):
__builtin__.file = orig_file

chattyfile = ContextManager()

with chattyfile:
f = file('x.txt', 'w')
f.write('hello')
f.close()
file('x.txt')

print chattyfile.opened

gives:

$ python chattyfile.py
opened <open file 'x.txt', mode 'w' at 0x19df0>
closed <closed file 'x.txt', mode 'w' at 0x19df0>
opened <open file 'x.txt', mode 'r' at 0x19e48>
[<open file 'x.txt', mode 'r' at 0x19e48>]

Warning: I did not test this more than you see.
Notice also that overriding the builtins is fine
for debugging purposes (it is perhaps the only good
use case for this feature, together with testing, for mock objects).
You are expected to use it as follows:

from chattyfile import chattyfile
from mylibrary import main

with chattyfile:
main()

and all calls to 'file' will be tracked down.
Since 'open' is basically an alias for 'file'
(they were exactly the same in Python 2.4)
you could also track 'open' in the same way.
If you are using Python 2.4 you can use the same
trick, but in a less clean way, using a try ..finally
instead of the context manager.

Michele Simionato
Jul 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Guyon Morée | last post by:
recently i've visited SARAH, the academic supercomputer in Amsterdam, Holland. this is next to the CWI, where Guido founded Python.... ....Yeah!...
1
by: Matthew Wilson | last post by:
Hi - I wrote this program: import Tkinter root = Tkinter.Tk() root.title('tkfun is tktastic!') cc = Tkinter.Canvas(root, width=400, height=400, bg="white")
12
by: Stephen Ferg | last post by:
I've just spent several very frustrating hours tracking down a bug in one of my programs. The problem was that I was writing text to a file, and when I was done I coded f.close when I should...
20
by: Mark Hahn | last post by:
Prothon is pleased to announce another major release of the language, version 0.1.2, build 710 at http://prothon.org. This release adds many new features and demonstrates the level of maturity...
3
by: Mike Monaghan | last post by:
I'm rather new to python but a long time programmer. I think I've covered my bases so I hope this isn't somthing obvious. I'm running ActiveState PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) ...
0
by: Mark Sandler | last post by:
Hi, When i create a process using popen and then if i decide that i am not interested in keeping the process pipes anymore, and I forget the correspond variables . Then, if python tries to destroy...
3
by: Sullivan WxPyQtKinter | last post by:
Hi,there. Sometimes a python CGI script tries to output great quantities of HTML responce or in other cases, it just falls into a dead loop. How could my client close that CGI script running on the...
0
by: Irmen de Jong | last post by:
I'm having some troubles with closing sockets using Python 2.5b1 Simply closing a client socket (on the server side) doesn't seem to actually shutdown the socket anymore. A connected client simply...
0
by: Steve Ingram | last post by:
Found out what I'd done, and it wasn't py2exe causug the problem. I wasn't closing the main dialog properly, I was calling Close() instead of Destroy(), so the dialog stayed in memory, basically it...
1
by: johnny | last post by:
I am getting following connection error from my python script: conn.close() AttributeError: adodb_mysql instance has no attribute 'close' Here is my relevant code below: def worker(tq):...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.