Search code examples
pythonfileioglob

storing text into string buffer from multiple files using python


I want to extract text from multiple text files and the idea is that i have a folder and all text files are there in that folder.

I have tried and succesfully get the text but the thing is that when i use that string buffer somewhere else then only first text file text are visbile to me.

I want to store these texts to a particular string buffer.

what i have done:

import glob
import io

Raw_txt = " "
files = [file for file in glob.glob(r'C:\\Users\\Hp\\Desktop\\RAW\\*.txt')]
for file_name in files:
    
    with io.open(file_name, 'r') as image_file:
        content1 = image_file.read()
        Raw_txt = content1
        print(Raw_txt)        

This Raw_txt buffer only works in this loop but i want this buffer somewhere else.

Thanks!


Solution

  • I think the issue is related to where you load the content of your text files. Raw_txt is overwritten with each file. I would recommend you to do something like this where the text is appended:

    import glob
    
    Raw_txt = ""
    files = [file for file in glob.glob(r'C:\\Users\\Hp\\Desktop\\RAW\\*.txt')]
    for file_name in files:
        with open(file_name,"r+") as file:
            Raw_txt += file.read() + "\n" # I added a new line in case you want to separate the different text content of each file
    print(Raw_txt)
    

    Also in order to read a text file you don't need io module.