You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从同一目录下的多个文本文件创建DataFrame

Python 从同目录多文本文件创建 DataFrame

前提说明

假设每个文本文件的格式为每行一个键值对(如 Key: Value),每个文件对应一条完整的数据记录。

实现步骤

  1. 导入所需库
import pandas as pd
import os
  1. 定义解析单个文本文件的函数
def parse_text_file(file_path):
    data = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            # 分割键和值,只分割第一个冒号(避免值里含冒号)
            key, value = line.split(':', 1)
            data[key.strip()] = value.strip()
    return data
  1. 遍历目录并收集所有数据
# 目标目录(当前目录用 '.')
target_dir = '.'
# 获取目录下所有 .txt 文件
txt_files = [f for f in os.listdir(target_dir) if f.endswith('.txt')]

# 解析所有文件
all_records = []
for file in txt_files:
    file_path = os.path.join(target_dir, file)
    record = parse_text_file(file_path)
    # 可选:添加文件名作为列,方便溯源
    record['filename'] = file
    all_records.append(record)
  1. 转换为 DataFrame
df = pd.DataFrame(all_records)
# 查看结果
print(df.head())

注意事项

  • 如果文本文件编码不是 utf-8,请调整 open 函数的 encoding 参数(如 gbk)
  • 若键值对分割规则不同(比如用其他分隔符),修改 split 方法的参数即可
  • 可以根据需求对缺失值进行处理(如 df.fillna())

内容的提问来源于stack exchange,提问作者Hemanth Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:06:39