python - 将循环中的数据框写入多个 Excel 文件
问题描述
我有 500 个 excel 文件,从每个文件中我必须跳过开始的 4 行并选择几列。我可以为每个具有特定列的文件创建新的 excel 文件,或者我可以在 SQL Server 中推送数据。
我需要创建一个可以读取所有文件并执行所需过程并以 excel 或 SQL 格式给我输出的函数。
解决方案
使用os
库来处理文件系统很方便。
该函数clean_one
来自您的代码,并进行了少量更改。该函数clean_all
适用clean_one
于目录中的所有文件root
(在我的代码'os.getcwd` [当前工作目录] 中):
import os
import pandas as pd
def clean_one(path, n):
df = pd.read_excel(path, skiprows = 4)
col_list = ['Emp Code', 'Emp Name', 'Net Salary', 'Gross Earnings', 'Provident Fund',
'Provident Fund_A', 'Profession Tax', 'ESIC Deduction', 'ESIC Deduction_A',
'Gross Deductions', 'Net Salary','Salary Bank', 'Salary Account No',
'IFSC Code', 'PAN', 'Location', 'PF_Membership_No', 'State For PT']
df.to_excel('File_%d.xlsx' % n, columns = col_list)
def clean_all(root):
for n, filepath in enumerate(os.listdir(root)):
path = os.path.join(root, filepath)
clean_one(path, n)
if __name__ == "__main__":
root = os.getcwd() # Replace it with necessary directory
clean_all(root)
推荐阅读
- mysql - 从 MySQL Workbench 连接到 SiteGround MySQL 数据库的“无法连接到数据库服务器”错误
- c++ - 模板实例化期间第二遍名称查找的静态与匿名名称空间的差异
- node.js - 如何将 facebook shop 集成到 react js、node js 或 php 应用程序中
- python - 加密的字符串与相同的字符串 python 的值不同
- kubernetes - 第一个参数未传递给 kubernetes 部署中的映像
- apache-spark - docker-compose.yml spark/hadoop/hive 三个数据节点
- java - Hashmap 代码未通过所有测试用例
- css - 在 ::After 伪元素 CSS 中的两个单词之间添加空格
- ios - Flutter firebase 消息传递 iOS 配置文件
- javascript - 为什么 Angular 服务的共享数据没有在 html 中更新?