Hi,
i have opened a file from a python sript using built in function 'file'. after reading data from that file, i closed the file descriptor and tried to delete the file but it gives an error that file is being used by another process whereas none of the process is using that file. If i manually select that file and delete it then it works. Following is the part of my script...

temp_file = file("temp_file.txt",'r')
while("some condition"):
msg = temp_file.readline().strip()
......................
...................
temp_file.close()
os.remove("temp_file.txt")

I think this probably has to do with Python's garbage collection. The file might not be closed at the exact moment you close it. You can let the program sleep for say one second, or try putting the read() through the close() in a function and call the function. All references should be destroyed when you exit the function. You should then be able to delete immediatly after exiting the function, but that's just my theory. Please post back if you come up with a solution, as others will want to know in the future.

Either you don't know what you're talking about, or I don't know what I'm talking about.

IO operations are synchronous in python unless an asynchronous operation is explicitly requested. This means that the program will block (execution will stop and wait) until the operation has either completed or failed. When you call close(), the program will not execute the next line until the file is indeed closed (or some error has prevented it from closing, in which case it throws an exception). Garbage collection has nothing to do with this, although file objects in python do close when they go out of scope (I believe this is a separate feature).

My suggestsions:
1. Is your close wrapped in a try block? Make sure it's not throwing an exception.

2. Make sure your program has enough permissions to delete the file (it may have enough to read, but not enough to modify or delete it). Common trap: This happens if the file is in Program Files or other "protected" directories under vista.

EDIT: Actually, suggestion 2 is bogus given the error it gives you. New suggestion:

I remember reading in the documentation that the file constructor shouldn't be used explicitly, but the function open should be used instead (takes the same arguments). Try opening the file with open() instead and see what it says.

EDIT EDIT: Even when I use file() I can still remove the file immediately after reading, so i don't know what the problem is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.