在for循环中打开一个文件并写入一个新文件



我正试图通过在for循环下将数据写入新的文本文件。它有点工作,但它不写所有的数据,我需要在文件中。有人能帮帮我吗?

下面是代码:
def process_images(base_file, output_dir, labels_path, l_out, sample_size):
base_file = base_file 
output_dir = output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
list_ims = sorted(os.listdir(base_file))
for counter, img in enumerate(list_ims):
if counter > sample_size:
print('Reached the end of the sample size')
break
else:
print('processing image number {} with name {}'.format(counter, img))
im = cv.imread(os.path.join(base_file, img))
output_path = os.path.join(output_dir, img)
result = face_detector(counter, im, output_path)
if result:
with open(labels_path, 'r') as d:
with open(l_out, 'w+') as f:
lines = d.readlines()[1:]
for line in lines:
file_name = line.split('/')[0].split()[1]
if file_name == img:
f.write(line)
else:
continue

人脸检测器是另一个函数,如果图像中有人脸,则输出true。如果result为true,则该函数应该加载文件并在文件中搜索img名称。如果发生这种情况,它应该将该文件名写入另一个文本文件。

我遇到的问题是,它只在循环中的第一次迭代中这样做,而不是其他迭代。我没有得到任何错误,只是其他图像名称没有写入新的文本文件。

您需要打开带有‘a’选项的文件。

with open(l_out, 'a') as f:

相关内容

最新更新