'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)


Solution 1:[1]

  1. You should use " instead of “
  2. To get the first item from a list use [0] and not [1]
  3. You don't need os.path.basename, os.listdir() already returns just the files name as string.

Other than that it seems okay to me, now you just have to save it to a file:

import os
with open("names_file.txt", "w", encoding="utf-8") as f:
    for filename in os.listdir("/my_dir/")
        base_name = filename.split("_")[0]
        print(base_name)
        f.write(filename+"\n")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ewz93