【问题标题】:creating a dataframe from contents of multiple files in a folder从文件夹中多个文件的内容创建数据框
【发布时间】:2020-08-23 06:26:36
【问题描述】:

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

【问题讨论】:

  • 不是machine-learningoperating-systemjupyter 问题 - 请不要向无关标签发送垃圾邮件(已删除)。

标签: python pandas file directory


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2017-02-17
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多