使用python将文本从多个文件存储到字符串缓冲区



我想从多个文本文件中提取文本,其想法是我有一个文件夹,所有文本文件都在该文件夹中。

我已经尝试并成功地获得了文本,但问题是,当我在其他地方使用字符串缓冲区时,只有第一个文本文件文本对我来说是可见的。

我想把这些文本存储到一个特定的字符串缓冲区。

我所做的:

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)

这个Raw_txt缓冲区只在这个循环中工作,但我想把这个缓冲区放在其他地方。

谢谢!

我认为这个问题与您在哪里加载文本文件的内容有关。CCD_ 1被每个文件覆盖。我建议你做这样的事情,在这里添加文本:

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)

此外,为了读取文本文件,您不需要io模块。

最新更新