簡體   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