使用Python将文本存储到来自多个文件的字符串缓冲区中

发布于 2025-01-20 20:14:29 字数 595 浏览 2 评论 0原文

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

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

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

我做了什么:

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 缓冲区仅在这个循环中工作,但我希望这个缓冲区在其他地方。

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

懒的傷心 2025-01-27 20:14:30

我认为这个问题与您加载文本文件内容的位置有关。
Raw_txt 会被每个文件覆盖。
我建议您在附加文本的情况下执行类似的操作:

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 模块。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文