首页 > 解决方案 > 从文件夹中多个文件的内容创建数据框

问题描述

我们需要编写一个程序来访问给定文件夹中的所有文件。每个文件都包含一个单行字符串,我们需要将文件名以及文件内容存储在数据框中并返回 csv 文件。如何解决这个问题?

标签: pythonpandasfiledirectory

解决方案


您没有明确说明要打开什么文件,因此假设它是 .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'))

推荐阅读