Python: Dissagreement between os.isfile() and os.listdir() -
i want remove file os.remove(), , work on remaining files in directory. however, find os.listdir() still includes erased files when grow beyond size. "ok", thought, "os.remove() works asynchronously. no big deal, i´ll utilize os.path.isfile() check if file has been removed yet". turned out not work. next code exemplifies problem:
import os open("test/test.txt", 'w') file: _ in range(100): file.write("spam") print os.path.isfile("test/test.txt") print os.listdir("test/") os.remove("test/test.txt") print os.path.isfile("test/test.txt") print os.listdir("test/")
this creates little file of 400 bytes. output expected:
true ['test.txt'] false []
but when number of "spam"s written increased 10 000 000 (a 40mb file), next output occurs:
true ['test.txt'] false ['test.txt']
so, isfile() quite aware file has been erased, listdir() hasn´t caught on yet.
is there more robust way of checking if file exists, agree next listdir() call?
tested python 2.7 on windows 7, should matter.
----edit
i have no intention open files right away; want display files remaining in directory in listbox. sense opening every file check if it´s there uncalled for, perhaps pythonic way of doing things?
in windows, if delete file that's open else (with file_share_delete), it's not deleted until it's closed. instead, entry remains there, marked "delete-pending" (and can't open obscure error). think cause discrepancy - os.path.isfile
sees exists not "regular file" anymore.
if case, os.path.exists
should homecoming true
.
one possible solution in case list files (with additional benefit of filtering out directories , such), i.e
print [f f in os.listdir(path) if os.path.isfile(os.path.join(path,f))]
of course, gives chance race status when changes while you're querying entries. in case, it's unavoidable unless have os supports transactions scheme calls.
python python-2.7
No comments:
Post a Comment