python - 有没有办法使用 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)
这是我的输出:
我的问题是我的输出只需要一个文件并显示其内容。显然,我在我的代码中将路径和文件名定义为一个文件,但我对如何以一种加载所有文件并分别输出其每个内容的方式编写路径感到困惑。有什么建议么?
解决方案
使用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
推荐阅读
- html - 防止同时播放多个 youtube iFrames 视频
- php - 学说迁移与数据
- android - 取消 ApplePay 和 GooglePay 对话框
- php - 安装 JSON Web 令牌和作曲家后,我的 __autoload 功能不起作用
- r - R:删除变量(列)中的观察值(行)
- snowflake-cloud-data-platform - 更改数据捕获 (CDC) - 在 S3 暂存文件和雪花表之间定期同步数据集
- javascript - 如何检查该元素是否具有赛普拉斯中的任一类?
- keras - 解释 keras.predict 的奇怪输出
- powershell - Powershell 提取最近 n 分钟的日志文件内容
- javascript - 恢复 Fiori 应用程序状态