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

Save first word in files names in another file

I have a folder that has lots of files with the format name1_name2_xxxx.xlsx. I want to save name1 of each file in this folder in a new text file

I tried this but it’s not working, any advice?

import os
for filename in os.listdir("/my_dir/")
    n=os.path.basename(filename)
    nn=n.split("_")
    nnn=n[1]
    print(n)

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

>Solution :

There is no need to use basename, you can just split the filename by "_" and take the first element in the array.

In addition, in order to create a file and write the first part of each filename to it, use with open.

Putting it all together:

import os

with open("first_part.txt", 'w') as result_file:
    for filename in os.listdir(“/my_dir/”):
        first_part = filename.split("_")[0]
        result_file.write(first_part + "\n")
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