Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

select the first of two or more filenames and save only the first

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading