繁体   English   中英

我需要从多个 csv 文件名中捕获日期,并使用 Python 在每个文件中将该日期添加为新列

[英]I need to capture date from multiple csv filenames and add that date in each file as a new column using Python

I need to capture date from multiple csv filenames and add that date in each file as a new column using Python, I have this code that works well with Excel files and I am trying to do exactly the same with CSV files, If someone could help我将不胜感激。

文件名如下... Scan_05-22-2021.csv Scan_05-23-2021.csv Scan_05-24-2021.Z628CB5675FF524F3EZFEE88 等。

Excel 代码有效..

import openpyexcel
import os
import pandas as pd
import glob
import csv

from openpyexcel import load_workbook
import os

path_to_xls = os.getcwd() # or r'<path>'

for xls in os.listdir ('C:\Python'):
    if xls.endswith(".csv") or xls.endswith(".xlsx"):
        f = load_workbook(filename=xls)
        sheet = f.active
        # Change here the name of the new column
        sheet.cell(row=1, column=25).value = "DateTest"
        for i in range(sheet.max_row-1):
            #xls.split('_')[1][:-5]    #kaes value of Col1 and dumps/overwrites in column 3
            sheet.cell(row=i+2, column=25).value = xls.split('_')[1][:-5]

                f.save(xls)
                f.close()

你应该可以用 pandas 做到这一点

使用 pd.read_csv 将文件加载为 DataFrames,您可以使用 iterrows 方法将 go 任何行和简单的 append 用于新文件。

这个备忘单可能有用

祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM