python - 有没有办法使用 Python 从目录中的所有文件加载数据?

标签 python python-3.x glob

我的问题:有没有一种方法可以使用 Python 从目录中的所有文件加载数据

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

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

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

/home/文件/wow.txt “所有内容” /home/文件/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)

这是我的输出:

enter image description here


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

最佳答案

使用 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

关于python - 有没有办法使用 Python 从目录中的所有文件加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730885/

相关文章:

python - 如何在另一个 python 脚本的循环内调用并运行 python mainmodel.py?

python - 使用 numpy 获取切片后剩余的内容

python - 合并具有相同键的字典列表

python - python3中的段错误(C)

python - 检查文本列 pandas 中停用词的数量

perl - 如何区分符号表和常规哈希变量?

Python OR'ing 数组在一起

python-3.x - Kivy:已弃用功能的替代方案

c - POSIX:glob() 只找到第一个匹配项

javascript - 在 JavaScript 中是否有类似 glob 但用于 URL 的东西?