how to print folder name in python?

266 views Asked by At

I am trying to read multiple folders for a specific text file using glob.glob to search in all folders. I wanted to print only the folder name instead of folder name/file.txt.

with open ('input.txt', 'w') as i:
    for files in glob.glob ('*/*.txt'):
        print (files)

I want my output to be like

folder1
folder2
folder3

instead of

folder1/file.txt
folder2/file2.txt

I saw many posts where they used os.path....which I did understand clearly

1

There are 1 answers

0
Mithilesh_Kunal On

Solve this with string functions. Try this code.

with open ('input.txt', 'w') as i:
    for files in glob.glob ('*/*.txt'):
        print(files.split("/")[0])

Explanation:

We are splitting the filename with / character. This results in a list with two items folder_name and file_name. Using indexing, we are fetching the first item with index 0.

To test this try below code -

a = [ "folder1/file.txt", "folder2/file.txt"]
for item in a:
    print(item.split("/")[0])