Python - 将多个Excel文件转换为CSV并覆盖旧行

2024-09-29 06:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

早上好, 我正在尝试将多个Excel文件转换为CSV。这是我的密码:

import os
import pandas as pd
import csv 

counter = 0   
for file in os.listdir():
    if file.endswith(".xlsm"):            
        if counter == 0:
            df_xlsmtocsv = pd.read_excel(file, 'Sheet2', index_col=None ) 
            df_xlsmtocsv .drop(df_xlsmtocsv .head(1).index,inplace=True) 

            print(df_qctocsv)
            with open('items.csv', 'w', encoding = "utf-8") as f:
                df_xlsmtocsv .to_csv(f, sep=',', header=None, index_label=None, index=False)
            counter += 1
        else:      
            df_xlsmtocsv = pd.read_excel(file, 'Sheet2', index_col=None, dtype = str)  
            df_xlsmtocsv .drop(df_xlsmtocsv .head(1).index,inplace=True)
            with open('items.csv', 'a', encoding = "utf-8") as f:

                df_xlsmtocsv .to_csv(f, sep=',', header=None, index_label=False, index=False, quotechar='"', quoting=csv.QUOTE_ALL)

您可以看到我能够列出文件夹中的所有xls文件,并将其转换为一个csv。这些文件具有以下字符串格式:

005-72_b_linux_–_april_2017
005-73_a_linux_–_may_2017
005-75_b_linux_–_july_2017
005-76_d_linux_-_august_2017

问题:如果我在2017年4月的文件中有一行“X”,并且在2017年5月更新了同一行,那么我想覆盖csv文件中2017年4月的旧行。但我上面的解决方案无法按月份字符串识别文件


Tags: 文件csvimportnonefalsedfindexif