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