列表理解以打开 CSV 文件 - Python

问题描述

我正在尝试创建一个列表理解来对两个 .csv 文件执行读/写操作。我需要以 .xlsx 格式打开原始文件,然后将它们写入 .csv 并将它们声明为用于基本读/写功能的 Pandas 数据帧。我的主要问题是使用“打开”函数来打开相应的 .csvs,而无需对文件名本身的后缀进行硬编码。下面是我目前用来将 .xlsx 文件写入 .csv 格式的代码,它是可行的,但如果可能的话,我想将其转换为列表理解……非常感谢任何见解!

原始脚本(“for”循环):

import os
import glob
import pandas as pd

path = "C:\\users\\mdl518\\Desktop\\"

for file in glob.glob(os.path.join(path,"*.xlsx")):  # loop through the .xlsx files
    if file.endswith("firstname.xlsx"):
        xlsx_1 = pd.read_excel(file)
        with open(os.path.join(path,file[:-5] + '_test1.csv'),'w',newline='') as f:
            xlsx_1.to_csv(f,index=None,header=True)
        for file in glob.glob(os.path.join(path,"*.csv")):
            df=pd.read_csv(file)
    if file.endswith("secondname.xlsx"):
        xlsx_2 = pd.read_excel(file)
        with open(os.path.join(path,file[:-5] + '_test2.csv'),newline='') as f:
            xlsx_2.to_csv(f,"*.csv")):
            if file.endswith("test2.csv"):
               df2=pd.read_csv(file) 

所需的脚本(更清晰的列表理解,类似于以下内容):

output = [pd.read_excel(i),pd.to_csv for i in glob.glob(os.path.join(path,"*.xlsx"))]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...