我需要在我的代码中更改什么以避免 sheetname.startswith in Python 的工作表?
What do i need to change in my code to avoid sheets by sheetname.startswith in Python?
我当前的代码能够按需执行并根据以特定字符串开头的文件名对所有 sheet 进行更改。但是,我刚刚意识到文件中的一些 sheets 在未来的几个月中可能会有稍微不同的名称。
我的代码-
import pandas as pd
from openpyxl import load_workbook
import os
cols_to_drop = ['PSI ID','PSIvet Region','PSIvet region num']
column_name_update_map = {'Account name': 'Company Name','Billing address':'Address','Billing city':'City'}
for file in os.listdir("C:/Users/hhh/Desktop/gu/python/PartMatching"):
if file.startswith("PSI"):
dfs = pd.read_excel(file, sheet_name=None)
output = dict()
for ws, df in dfs.items():
if ws in ["Added"]:
continue
if ws in ["New Members 03.22", "PVCC"]: #sheets to avoid
temp = df
temp['Status'] = "Active" if ws == "All Members" else "Cancelled"
#drop unneeded columns
temp = df.drop(cols_to_drop, errors="ignore", axis=1)
#rename columns
temp = temp.rename(columns=column_name_update_map)
#drop empty columns
temp = temp.dropna(how="all", axis=1)
temp['Partner'] = "PSI"
output[ws] = temp
writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx')
for ws, df in output.items():
df.to_excel(writer, index=None, sheet_name=ws)
writer.save()
writer.close()
我的目标是让我当前的代码避免 sheet 名称以“新成员”开头的代码。但正如您在我的代码中看到的那样,我必须特别提到 New Members 03.22。这个 sheet 下个月将被命名为 New Members 04.22,因此不会与我在计划任务中 运行 的代码兼容。我试过 if ws.startswith in ["New Members 03.22", "PVCC"]: 但什么也没发生。
startswith
一次只能用一个字符串,所以需要分手测试
if any(ws.startswith(x) for x in ["New Members", "PVCC"]):
我当前的代码能够按需执行并根据以特定字符串开头的文件名对所有 sheet 进行更改。但是,我刚刚意识到文件中的一些 sheets 在未来的几个月中可能会有稍微不同的名称。 我的代码-
import pandas as pd
from openpyxl import load_workbook
import os
cols_to_drop = ['PSI ID','PSIvet Region','PSIvet region num']
column_name_update_map = {'Account name': 'Company Name','Billing address':'Address','Billing city':'City'}
for file in os.listdir("C:/Users/hhh/Desktop/gu/python/PartMatching"):
if file.startswith("PSI"):
dfs = pd.read_excel(file, sheet_name=None)
output = dict()
for ws, df in dfs.items():
if ws in ["Added"]:
continue
if ws in ["New Members 03.22", "PVCC"]: #sheets to avoid
temp = df
temp['Status'] = "Active" if ws == "All Members" else "Cancelled"
#drop unneeded columns
temp = df.drop(cols_to_drop, errors="ignore", axis=1)
#rename columns
temp = temp.rename(columns=column_name_update_map)
#drop empty columns
temp = temp.dropna(how="all", axis=1)
temp['Partner'] = "PSI"
output[ws] = temp
writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx')
for ws, df in output.items():
df.to_excel(writer, index=None, sheet_name=ws)
writer.save()
writer.close()
我的目标是让我当前的代码避免 sheet 名称以“新成员”开头的代码。但正如您在我的代码中看到的那样,我必须特别提到 New Members 03.22。这个 sheet 下个月将被命名为 New Members 04.22,因此不会与我在计划任务中 运行 的代码兼容。我试过 if ws.startswith in ["New Members 03.22", "PVCC"]: 但什么也没发生。
startswith
一次只能用一个字符串,所以需要分手测试
if any(ws.startswith(x) for x in ["New Members", "PVCC"]):