我的问题:有没有一种方法可以使用 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)
这是我的输出:
我的问题 是我的输出只获取一个文件并显示其内容。显然,我在我的代码中将路径和文件名定义为一个文件,但我对如何以加载所有文件并分别输出其每个内容的方式编写路径感到困惑。有什么建议吗?
最佳答案
使用 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/