我有一個程序,我需要保留一些打開磁盤列表上的文件的對象,並在程序完成後刪除這些文件。不過,即使沒有更多的引用應該打開它的對象,Python似乎仍然保持打開文件。我已經能夠重現問題與純文件對象如下:Python是否保留對在列表中打開的文件的引用?
import os
filenames = ['a.txt', 'b.txt']
files = [open(f,'w') for f in filenames]
for f_object in files:
f_object.write("test")
del files[:]
for name in filenames:
os.remove(name)
當我在Windows上運行此我得到的錯誤
Traceback (most recent call last):
File ".\file_del.py", line 11, in <module>
os.remove(name)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'b.txt'
有趣的是它能夠刪除a.txt
沒有問題。即使引用該文件不存在,導致b.txt
文件被打開的原因是什麼?
更新
在原來的問題,我沒有訪問到文件關閉它們。相信我,我很想關閉這些文件。請參閱以下內容:
base_uri = 'dem'
out_uri = 'foo.tif'
new_raster_from_base_uri(base_uri, out_uri, 'GTiff', -1, gdal.GDT_Float32)
ds = []
for filename in [out_uri]:
ds.append(gdal.Open(filename, gdal.GA_Update))
band_list = [dataset.GetRasterBand(1) for dataset in ds]
for band in band_list:
for row_index in xrange(band.YSize):
a = numpy.zeros((1, band.XSize))
band.WriteArray(a, 0, row_index)
for index in range(len(ds)):
band_list[index] = None
ds[index] = None
del ds[:]
os.remove(out_uri)
更新2
我標誌着millimoose的回答如下正確的,因爲它修復該問題與我這裏介紹文件的抽象問題。不幸的是,它不適用於我使用的GDAL對象。爲了將來的參考,我深入挖掘並找到了未記錄的gdal.Dataset.__destroy_swig__(ds)
函數,這似乎至少關閉了與數據集關聯的文件。在刪除與數據集關聯的磁盤上的文件之前,我先調用它,並且似乎正常工作。
你有沒有...關閉文件? – Brian
我在這裏抽象了問題,在原始問題中,我從GDAL庫創建GIS數據集。我無權訪問GDAL對象引用的文件。引用計數是相同的。 – Rich
@Brian當對象被GCed時應該關閉文件。 – millimoose