Python - joining text files in multiple subfolders

Lokesh :

I have a folder with multiple subfolders. Within each subfolder I have multiple .txt files.

for root, dirs, files in os.walk(path):
    print(files)
Out:
['1.txt', '2.txt', '3.txt', '4.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt', '8.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']

I want to join the text files in each subfolder and return each as a single string.

I have tried the following:

for root, dirs, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            with open(os.path.join(root, file), 'r') as f:
                text = f.read()

However, I'm getting the text for each txt file as separate strings. I want them either in a list for each subfolder (like above) or join each txt in a subfolder into a single string and get an output of 4 strings rather than 23.

DBat :

You can use string concatenation at each read iteration like so:

for root, dirs, files in os.walk(path):
    text = ''
    for file in files:
        if file.endswith('.txt'):
            with open(os.path.join(root, file), 'r') as f:
                text += f.read()
    print(text)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386592&siteId=1