简体   繁体   中英

Python - joining text files in multiple subfolders

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM