Home > front end >  Save first word in files names in another file
Save first word in files names in another file

Time:02-13

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)

CodePudding user response:

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

CodePudding user response:

  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")
  • Related