【问题标题】:How to run a script over several files如何在多个文件上运行脚本
【发布时间】:2021-11-28 05:03:57
【问题描述】:

我正在尝试使用文件夹中的文件名创建数据框。之后,想法是读取该数据帧的每一行,识别它是一个文件,用它创建一个数据帧并运行脚本的其余部分以将一列替换为新值(最后一部分已经完成并且工作正常) .

所以,我首先阅读文件并将它们列在一个列表中:

path = os.getcwd()
files = os.listdir(path)
files

然后,我创建数据框:

df_file = pd.DataFrame (files, columns = ['Filename'])

此时我被卡住了。现在我有了带有文件名的数据框。 Python 如何将每一行识别为一个文件并将数据保存在数据框中?

PS.:我这样做是因为我的老老板告诉我的。但是说明不是很具体,我迷路了。

谢谢!

【问题讨论】:

  • 您查看的是什么类型的文件? xlsx?
  • 是的!这是一个 xlsx 文件。
  • 我下面的回答应该会有所帮助!

标签: python pandas file


【解决方案1】:

我不太确定您要识别的文件类型,如果它们是 xlsx 文件,以下内容应该会有所帮助:

import os
import pandas as pd


# You don't need to identify the current path
# path = os.getcwd()
files = os.listdir()


df_file = pd.DataFrame(files, columns=['Filename'])
# You are right up to this point

# Read all the rows in this main dataframe
for file in df_file['Filename']:
    # If it is an excel file, proceed to run functions on it
    # If it is a different type of file (e.g. csv) just swap "xlsx" out for "csv"
    if "xlsx" in file:
        df = pd.read_excel(file)
        # Continue...

【讨论】:

  • 没问题,很高兴为您提供帮助
猜你喜欢
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多