python - 从文件夹中多个文件的内容创建数据框
问题描述
我们需要编写一个程序来访问给定文件夹中的所有文件。每个文件都包含一个单行字符串,我们需要将文件名以及文件内容存储在数据框中并返回 csv 文件。如何解决这个问题?
解决方案
您没有明确说明要打开什么文件,因此假设它是 .txt 文件。您可以使用os.listdir(path)
获取存储在某个路径的所有文件的列表。然后加载文本文件并将内容和文件名附加到列表中。最后,创建一个 DataFrame 并保存到 csv。
import os
import pandas as pd
# set the path to your file location
path = r'path\to\Text'
# create a empty list, where you store the content
list_of_text = []
# loop over the files in the folder
for file in os.listdir(path):
# open the file
with open(os.path.join(path, file)) as f:
text = f.read()
# append the text and filename
list_of_text.append((text, file))
# create a dataframe and save
df = pd.DataFrame(list_of_text, columns = ['Text', 'Filename'])
df.to_csv(os.path.join(path, 'new_csv_file.csv'))
推荐阅读
- kentico - Kentico 11 API 能否以与使用 Kentico Cloud 相同的方式使用?
- java - 通过 JAXB 解组重用元素/类
- c# - 如何在 api 调用中传入多个类类型?
- vue.js - 在 vue 中将数据从一个组件发送到另一个组件
- apache-kafka - 在日志 4j 的 RollingFileAppender 中基于每月和日志保留 30 天的日志轮换
- java - 错误:尝试在空对象引用上调用接口方法“int java.util.List.size()”
- android - Firebase 身份验证和数据库链接
- swift - Swift:如何对尴尬但常规的 JSON 结构进行 DRY 可解码解析
- powershell - Powershell 脚本不会根据 where 子句返回事件日志结果
- javascript - 如何使用节点 js 读取上传到谷歌云存储的 JSON 文件的内容