如何将文件夹中的多个文本文件加载到python列表变量中

如何将文件夹中的多个文本文件加载到python列表变量中,python,Python,我有一个充满文本文档的文件夹,其中的文本需要加载到单个列表变量中 列表中的每个索引,都应该是每个文档的全文 到目前为止,我有这个代码,但它不工作以及 dir = os.path.join(current_working_directory, 'FolderName') file_list = glob.glob(dir + '/*.txt') corpus = [] #-->my list variable for file_path in file_list: text_file

我有一个充满文本文档的文件夹,其中的文本需要加载到单个列表变量中

列表中的每个索引,都应该是每个文档的全文

到目前为止,我有这个代码,但它不工作以及

dir = os.path.join(current_working_directory, 'FolderName')
file_list = glob.glob(dir + '/*.txt')
corpus = [] #-->my list variable
for file_path in file_list:
    text_file = open(file_path, 'r')
    corpus.append(text_file.readlines()) 
    text_file.close()
有更好的方法吗


编辑:将csv阅读功能(
read\u csv
)替换为文本阅读功能(
readlines()
)。

您只需
read()
中的每个文件,并将其附加到
语料库中,如下所示:

import glob
import os

file_list = glob.glob(os.path.join(os.getcwd(), "FolderName", "*.txt"))

corpus = []

for file_path in file_list:
    with open(file_path) as f_input:
        corpus.append(f_input.read())

print(corpus)
然后,每个列表条目将是每个文本文件的全部内容。注意,使用
readlines()
将为每个文件提供行列表,而不是原始文本

带着一份清单
file\u list=glob.glob(os.path.join(os.getcwd(),“FolderName”,“*.txt”))
语料库=[open(file).read()用于文件列表中的文件]

但是,这种方法可能会导致更多的资源使用,因为没有带有自动关闭每个文件的
部分。

我发现这是一种更简单的方法:

import os
import shutil
import csv
import sys

csv_file = "card.csv"

with open(csv_file, 'r') as f:
    reader = csv.reader(f)
    for i, row in enumerate(reader):
        if i == 0:
            print(i)
            pass    # Skip header row
        else:
            filename,filepath,x,y,w,h = row

            file2 = filename + ".txt"    
            file1 = open(file2,"a")#append mode 
            file1.write("%s\n%s\n%s\n%s\n" % (x, y, w,h)) 
            file1.close() 
    import glob


    corpus = []

    file_list = glob.glob("Foldername/*.txt")
    for file_path in file_list:
        with open(file_path, 'r') as file_input:
           corpus.append(file_input.read())
    print (corpus)
  • 使用模块
  • 使用
    Path()
    创建路径的
    pathlib
    对象(或使用),并使用(或)查找与特定模式匹配的文件。
    • files=(Path().cwd()/'FolderName').glob('*.txt')
      • /
        用于将文件夹(扩展)添加到
        pathlib
        对象
    • 备选方案:
      • files=Path('./FolderName').glob('*.txt')
      • files=Path('e:/PythonProjects/stack_overflow/t-files/').glob('*.txt')
  • 可用于将文本读入
    列表
    ,无需使用。
    • text=[f.read_text()表示文件中的f]
    • 备选方案:
      • text=[f.open().read()表示文件中的f]
      • text=[f.open().readlines()用于文件中的f]
        -创建
        列表的
        列表的
从pathlib导入路径
#获取文件
files=(Path().cwd()/'FolderName').glob('*.txt'))
#将每个文件中的文本写入具有列表理解的列表中
text=[f.读取文件中f的[u text()]
用于循环
备选方案 选择1
files=Path('./FolderName').glob('*.txt'))
text=list()
对于文件中的文件:
text.append(file.read\u text())
选择2
  • 使用
    .read()
    可以打开文件,并将文件文本读入列表
files=Path('./FolderName').glob('*.txt'))
text=list()
对于文件中的文件:
将file.open()作为f:
text.append(f.read())
  • 也看到

在回答中添加一些解释