首页 > 解决方案 > 有没有办法使用 Python 从目录中的所有文件加载数据?

问题描述

我的问题:有没有办法使用 Python 从目录中的所有文件加载数据

输入:获取我给定目录中的所有文件(wow.txt、testting.txt 等)

流程:我想通过一个def函数运行所有文件

输出:我希望输出是它下面的所有文件名及其各自的内容。例如:

/home/file/wow.txt "所有内容" /home/file/www.txt "所有内容"


这是我的代码:

# Import Functions
import os
import sys

# Define the file path
path="/home/my_files"
file_name="wow.txt"

#Load Data Function
def load_data(path,file_name):
    """
    Input  : path and file_name
    Purpose: loading text file
    Output : list of paragraphs/documents and
             title(initial 100 words considered as title of document)
    """
    documents_list = []
    titles=[]
    with open( os.path.join(path, file_name) ,"rt", encoding='latin-1') as fin:
        for line in fin.readlines():
            text = line.strip()
            documents_list.append(text)
    print("Total Number of Documents:",len(documents_list))
    titles.append( text[0:min(len(text),100)] )
    return documents_list,titles

#Output
load_data(path,file_name)

这是我的输出:

在此处输入图像描述


我的问题是我的输出只需要一个文件并显示其内容。显然,我在我的代码中将路径和文件名定义为一个文件,但我对如何以一种加载所有文件并分别输出其每个内容的方式编写路径感到困惑。有什么建议么?

标签: pythonpython-3.xglob

解决方案


使用glob

import glob
files = glob.glob("*.txt")           # get all the .txt files

for file in files:                   # iterate over the list of files
    with open(file, "r") as fin:     # open the file
        # rest of the code

使用os.listdir()

import os
arr = os.listdir()    
files = [x for x in arr if x.endswith('.txt')]

for file in files:                   # iterate over the list of files
    with open(file, "r") as fin:     # open the file
       # rest of the code

推荐阅读