I want to save files with these filenames:
filenames = [
'4_66\nNUC_66377\nAPPR\nWONDER',
'4_66\nNUC_66377\nAPPR\nCOT',
'8_21\nAKRO\nNUT\nAMY'
]
and if the filename starts with the same number before underscore, then write to file only the first filename.
So, I am doing:
for idx in range(len(filenames)-1):
if filenames[idx][0:2] != filenames[idx + 1][0:2]:
with open('./' + filenames[idx] + '.txt', 'w') as file:
file.write('111')
# save the last file
with open('./' + filenames[-1] + '.txt', 'w') as file:
file.write('111')
But if you run the code, it saves the second one!
'4_66\nNUC_66377\nAPPR\nCOT'
>Solution :
Rely on set containment check to only process the files with encountered unique custom prefix:
fn_set = set()
for f in filenames:
pfx = f[:f.find('_')] # prefix before underscore
if pfx not in fn_set:
f.write('yourdata')
fn_set.add(pfx)