使用python删除文件夹里excel中特定的列
下面是一个Python代码示例,用于删除文件夹中所有Excel文件中的特定列:
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)
该代码使用pandas库来读取和写入Excel文件,并使用os库来遍历文件夹中的所有Excel文件。在循环中,每个Excel文件都被读取到一个pandas dataframe中,然后指定的列被使用drop方法删除。最后,修改后的数据被写回原始文件中。请注意,此代码假定您的Excel文件都只有一个工作表,命名为“Sheet1”。如果您有多个工作表,您需要修改to_excel方法中的sheet_name参数
AI 优化版
原文地址:https://www.cveoy.top/t/topic/fKeq 著作权归作者所有。请勿转载和采集!