gpt4 book ai didi

python - Python 是否保留对在列表中打开的文件的引用?

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:39 24 4
gpt4 key购买 nike

我有一个程序,我需要在磁盘列表中保留一些打开文件的对象,并在程序完成后删除这些文件。然而,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) 函数,它似乎至少关闭了与数据集关联的文件。在删除磁盘上与数据集关联的文件之前,我首先调用它,这似乎有效。

最佳答案

循环变量f_object的作用域其实就是周围的函数/模块。这意味着即使您清除列表,它也会保留对迭代中最后一个文件的引用。以下工作正常:

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[:]
# Nuke the last reference.
del f_object

for name in filenames:
os.remove(name)

我想在您的原始代码中应该是 del band。或者,将循环移动到函数中以避免循环变量泄漏:

import os

def write_to_files(files):
for f_object in files:
f_object.write("test")

filenames = ['a.txt', 'b.txt']
files = [open(f,'w') for f in filenames]
write_to_files(files)

del files[:]

for name in filenames:
os.remove(name)

关于python - Python 是否保留对在列表中打开的文件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com