[英]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 me that would be much appreciated. 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我将不胜感激。
Filenames are as following... Scan_05-22-2021.csv Scan_05-23-2021.csv Scan_05-24-2021.csv and so on..文件名如下... Scan_05-22-2021.csv Scan_05-23-2021.csv Scan_05-24-2021.Z628CB5675FF524F3EZFEE88 等。
Excel code that works.. 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()
You should be able to do this with pandas你应该可以用 pandas 做到这一点
use pd.read_csv to load the files as DataFrames you can use the iterrows method to go ever rows and simply append to the new file.使用 pd.read_csv 将文件加载为 DataFrames,您可以使用 iterrows 方法将 go 任何行和简单的 append 用于新文件。
this cheatsheet could be of use这个备忘单可能有用
Good luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.