1

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

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.