yasser
yasser

Reputation: 31

Trying to reach all .txt files in Python

I have a folder which is "labels". In this folder, thera are 50 folders again and each of these 50 folder have .txt files. How can I reach these .txt files with using Python 2?

Upvotes: 1

Views: 51

Answers (2)

Reez0
Reez0

Reputation: 2689

If you just want to list the files in the folders:

import os


rootdir = 'C:/Users/youruser/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print (os.path.join(subdir, file))

Upvotes: 1

Filip Młynarski
Filip Młynarski

Reputation: 3612

Here's code that will go through all folders in labels and print content of txt files located inside them.

import os

for folder in os.listdir('labels'):
    for txt_file in os.listdir('labels/{}'.format(folder)):
        if txt_file.endswith('.txt'):
            file = open('labels/{}/{}'.format(folder, txt_file), 'r')
            content = file.read()
            file.close()

            print(content)

Upvotes: 1

Related Questions