Python 批量删除 Excel 文件指定列:代码示例
使用 Python 批量删除 Excel 文件指定列:代码示例
本文将介绍如何使用 Python 代码批量删除文件夹中所有 Excel 文件的特定列。示例代码使用 Pandas 库读取和写入 Excel 文件,并使用 OS 库遍历文件夹。
import os
import pandas as pd
dir_path = 'path/to/your/folder'
column_to_remove = 'column_name'
for file_name in os.listdir(dir_path):
if file_name.endswith('.xlsx'):
file_path = os.path.join(dir_path, file_name)
df = pd.read_excel(file_path)
df = df.drop([column_to_remove], axis=1)
with pd.ExcelWriter(file_path, engine='openpyxl', mode='w') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
代码说明:
- 使用
os.listdir()遍历文件夹中的所有文件。 - 使用
file_name.endswith('.xlsx')判断是否为 Excel 文件。 - 使用
pd.read_excel()读取 Excel 文件到 Pandas DataFrame 中。 - 使用
df.drop()删除指定列。 - 使用
pd.ExcelWriter()以写入模式打开 Excel 文件。 - 使用
df.to_excel()将修改后的 DataFrame 写入 Excel 文件。
注意:
- 此代码假设所有 Excel 文件只有一个工作表,名为 'Sheet1'。如果您有多个工作表,您需要修改
to_excel()方法中的sheet_name参数。 - 您可以根据需要修改
dir_path和column_to_remove变量。
通过此代码,您可以轻松地对文件夹中所有 Excel 文件进行批量操作,删除指定列,提高工作效率。
原文地址: https://www.cveoy.top/t/topic/opLv 著作权归作者所有。请勿转载和采集!