【问题标题】:How to iterate through a folder that contains csv files, extract each file's modified date and create a new column as " modified date" using Python如何遍历包含 csv 文件的文件夹,提取每个文件的修改日期并使用 Python 创建一个新列作为“修改日期”
【发布时间】:2022-01-14 02:49:59
【问题描述】:

做了一些研究,发现下面的 python 代码能够提取 csv 文件的修改日期。关于如何编写 python 代码来遍历包含多个 csv 文件的文件夹所需的帮助。对于每个文件,提取的修改日期将作为新列添加为文件夹中每个 csv 文件中的“日期”。

Python 代码:

from datetime import datetime
from os.path import getmtime

file = 'abc.csv'
datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')

output answer :
'01/15/2020'

【问题讨论】:

  • 您想根据您提供的输出答案在文件中添加另一列吗?假设有 100 行,那么您会将日期添加到日期列中 100 次吗?
  • 您好,先生,是的。这个想法是,如果我在一个文件夹中有 10 个 csv 文件,假设每个文件有 100 行,每个文件将有一个名为“日期”的新列名,并且新列将填充 csv 文件的修改日期。希望我解释清楚。谢谢你的帮助!

标签: python csv


【解决方案1】:

这是一个您可以对每个 csv 文件名调用的函数。您可以在 for 循环中遍历目录并每次调用此函数。

说明:

将新列date 添加到值为dateCreated 的csv file

参数:

  1. file : 正在编辑的 csv 文件名
  2. dateCreated :您在示例中计算的变量

返回:

import csv

def addDate(file,dateCreated):
  # Open a file and a temp file
  temp = "temp.csv"
  with open(file) as f, open(temp, "w") as o:
    rows = csv.reader(f)
    w = csv.writer(o)

    # Set the column name to date
    header = next(rows)
    header.append("date")
    w.write(header)
    #iterate over the rows and add the date
    for row in rows:
      row.append(dateCreated)
      w.write(row)
  os.rename(temp, file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2016-12-09
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多