Python在实际工作中的运用-指定目录内所有Excel文件转CSV

devtools/2025/3/1 12:47:16/

闲来无事浏览到《【办公自动化】使用Python批量处理Excel文件并转为csv文件》这篇博文,关于多层目录Excel转Csv在处理过程中略显繁复,而且灵活度不高,代码如下:

python">import pandas as pd
import os
from datetime import datetime
# 基础文件夹路径
base_dir = './sample_data'# 循环遍历到每一个excel文件并修改其文件类型为csv
for first_floor in os.listdir(base_dir):  # 遍历第一层second_floor_dir = base_dir+'/'+first_floor  # 获取第二层的文件路径for second_floor in os.listdir(second_floor_dir):  # 遍历第二层third_floor_dir = base_dir+'/'+first_floor+'/'+second_floor  # 获取第三层的文件路径for third_floor in os.listdir(third_floor_dir):  # 遍历第三层fourth_floor_dir = base_dir+'/'+first_floor+'/'+second_floor+'/'+third_floor  # 获取第四层的文件路径for file_dir in os.listdir(fourth_floor_dir):  # 遍历第四层file_name = file_dir.split('.')[0]  # 获取excel文件名称file_suffix = file_dir.split('.')[1]  # 获取excel文件后缀print(fourth_floor_dir)if file_suffix=='xlsx' or file_suffix=='xls': # 判断文件是否是excel文件df = pd.read_excel(fourth_floor_dir+'/'+file_dir)  # 读取excel文件df['Time'] = pd.to_datetime(df['Time'])df['Time'] = df['Time'].apply(lambda x:datetime.strftime(x,'%Y-%m-%d %H:%M:%S'))df.to_csv(fourth_floor_dir+'/'+file_name+'.csv',index=False)  # 将excel文件保存为csv文件os.remove(fourth_floor_dir+'/'+file_dir)  # 删除原来的excel文件

摘自《【办公自动化】使用Python批量处理Excel文件并转为csv文件》第二段“批量处理Excel文件并转为csv文件”

觉得此案例中处理过程比较死板,可以采用更简洁的代码完成此项工作,思路如下:首先可以通过遍历得到指定目录及其子目录下所有的Excel文件列表,然后再逐个将列表内的Excel文件转换为CSV保存到同一目录下即可。

完整代码如下:

python">import os
from pathlib import Path
import pandas as pd# 遍历目录得到Excel表格列表
def find_table_files(directory, extensions=('.xlsx', '.xls')):table_files = []for root, dirs, files in os.walk(directory):for file in files:if file.endswith(extensions):table_files.append(os.path.join(root, file))return table_files# 逐个将列表里表格转换为CSV文件
directory_path = f'd:\\xls'
files = find_table_files(directory_path)
for file in files:df = pd.read_excel(file)df.to_csv(f'd:\\xls\\ToCsv\\{Path(file).stem}.csv', index=False)
print(f'执行完毕')


http://www.ppmy.cn/devtools/163622.html

相关文章

dify镜像拉取不下来如何解决

# 启动docker(一定要先启动再添加dns) systemctl start docker #添加国境镜像和dns sudo vim /etc/docker/daemon.json { "registry-mirrors":[ "https://dockerpull.pw", "https://dockerhub.icu", "https://hu…

Redis 分布式锁

概念 在⼀个分布式的系统中,也会涉及到多个节点访问同⼀个公共资源的情况,此时就需要通过锁来做互斥控制,避免出现类似于 "线程安全" 的问题。但 C 的 std::mutex 只能在当前进程中⽣效, 在分布式的这种多个进程多个主机的场景下就…

C++核心指导原则: 源文件

C Core Guidelines 整理目录 哲学部分接口(Interface)部分函数部分类和类层次结构部分枚举部分资源管理部分表达式和语句部分性能部分并发和并行错误处理常量和不可变性泛型编程源文件 源文件规则 SF.1: Use a .cpp suffix for code files and .h for interface files if you…

微信小程序自定义导航栏,胶囊菜单按钮高度适配问题

抽离公共方法用条件编译对微信小程序&#xff0c;抖音小程序适配 公共组件模块建立一个导航模块 <template><view class"layout"><view class"navbar" ><view class"statusBar" :style"{height:getStatusBarHeight()p…

微信小程序记录用户在图书详情页面停留时间--即阅读时间,如果超过两小时,则每小时提醒用户一次

在微信小程序中记录用户在图书详情页面的停留时间&#xff0c;并根据条件&#xff08;如超过两小时&#xff09;进行提醒&#xff0c;可以通过以下步骤实现。以下是详细的实现方案&#xff1a; 1. 实现思路 记录进入页面的时间&#xff1a;当用户进入图书详情页面时&#xff0…

SpringSecurity踢出指定用户

SpringSecurity中可以使用 SessionRegistry 的实现类 SessionRegistryImpl 来获取session相关信息&#xff0c;可以通过这个实现类来踢出用户。 SpringSecurity配置 EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {AutowiredISysUser…

MR30系列分布式I/O:高稳定与高精准赋能锂电池覆膜工艺革新

在新能源行业高速发展的背景下&#xff0c;锂电池生产工艺对自动化控制的精准性和可靠性提出了更高要求。作为锂电池生产中的关键环节&#xff0c;覆膜工艺直接关系到电池的绝缘性能、安全性及使用寿命。面对复杂的工艺控制需求&#xff0c;明达技术MR30系列分布式I/O模块凭借其…

【Groovy】流程控制

1 选择结构 Groovy 中选择结构主要包含 if -else、switch 语句&#xff0c;并且可以返回结果。 1.1 if-else def score 85 if (score > 90) {println("优秀") } else if (score > 80) {println("良好") } else if (score > 60) {println("…