从工作簿名称列表中提取工作簿名称

Extracting workbook name from Workbook Name List

我是 python 的菜鸟。目前,我有一个正在通过 load_workbook 函数传递的工作簿名称列表。但是,我有一堆取决于工作簿的 if 语句。所以我需要解析他们的名字或找到另一种方法来检查工作簿。这是我的代码:

for x in range(0, len(allbooks)):

    wb = openpyxl.load_workbook(allbooks[x], keep_vba = True)
    print (wb)

    if wb == "Subportfolio 1.xlsm":
        ws = wb.worksheet("Positions")
        if datetime.datetime.today().weekday() == 6: #check if its sunday
            if ws.cells('D1') != "Price on %s" % last_friday: #check to see if date is last friday
                print ("Need to Update Subportfolio")
        elif ws.cells('D1') != "Price on %s" % d: #check to see if date is today
            print ("Need to Update Subportfolio")

    elif wb == "Mock Portfolio - He Yibo 2 (TMT).xlsm":
        ws = wb.worksheet("Positions")
        if datetime.datetime.today().weekday() == 6:
            if ws.cells('E1') != "Price on %s" % last_friday:
                print ("Need to Update Mock Portfolio - He Yibo 2 (TMT)")
        elif ws.cells('E1') != "Price on %s" % d:
            print ("Need to Update Mock Portfolio - He Yibo 2 (TMT)")

    elif wb == "Mock Portfolio - He Yibo 2 (Utilities).xlsm":
        ws = wb.worksheet("Positions")
        if datetime.datetime.today().weekday() == 6:
            if ws.cells('E1') != "Price on %s" % last_friday:
                print ("Need to Update Mock Portfolio - He Yibo 2 (Utilities)")
        elif ws.cells('E1') != "Price on %s" % d:
            print ("Need to Update Mock Portfolio - He Yibo 2 (Utilities)")

我没有使用过那个模块,但这是我所知道的另一种方法:

假设您的工作簿位于同一个文件夹中,您可以使用 os 模块获取文件名列表。类似于以下内容:

import os
import xlrd
os.chdir("c:/mypath/myfolder")
my_filenames = os.listdir()
for filename in my_filenames:
    if filename == 'desired file.xls'
        my_workbook = xlrd.open_workbook(my_filenames[i])

然后您可以解析 my_filenames 并使用 xlrd 模块按名称打开所需的工作簿。当然,此模块中的函数给出的索引不同。

这第一部分确实不是很pythonic。在 Python 中,您不需要索引来遍历列表。 Python 中的 for 在大多数其他语言中充当 foreach,所以这个

for x in range(0, len(allbooks)):

    wb = openpyxl.load_workbook(allbooks[x], keep_vba = True)

可以缩短为

for book in allbooks:
    wb = openpyxl.load_workbook(book, keep_vba = True)

另一种改进方法是将所有 elif 语句替换为字典或命名元组。如果只有单元格发生变化,您可以使用 dict

轻松完成此操作
books = {'Subportfolio 1.xlsm': 'D1', 'Mock Portfolio - He Yibo 2 (TMT).xlsm', 'E1'} #etcetera
for book, important_cell in books.items():
    wb = openpyxl.load_workbook(book, keep_vba = True)
    ws = wb.worksheet("Positions")
    message = 'Need to Update %s' % book
    if datetime.datetime.today().weekday() == 6: #check if its sunday
        if ws.cells(important_cell) != "Price on %s" % last_friday: #check to see if date is last friday
            print (message)
    elif ws.cells(important_cell) != "Price on %s" % d: #check to see if date is today
        print (message)

每个工作簿有更多参数

当每个工作簿有更多参数时,例如工作表名称,您可以通过几种方式做到这一点

命名元组

如果是固定数量的参数不会变化,一个namedtuple是一个很方便的结构:

myworkbook = namedtuple('myworkbook', ['filename', 'sheetname', 'cell'])
allbooks = [myworkbook('filename0', 'sheetname0', 'cell0'),
            myworkbook('filename1', 'sheetname1', 'cell1'),...]
for book in allbooks:
    wb = openpyxl.load_workbook(book.filename, keep_vba = True)
    ws = wb.worksheet(book.sheetname)
    message = 'Need to Update %s' % book.filename
    if datetime.datetime.today().weekday() == 6: #check if its sunday
        if ws.cells(book.cell) != "Price on %s" % last_friday: #check to see if date is last friday
            print (message)
    elif ws.cells(book.cell) != "Price on %s" % d: #check to see if date is today
        print (message)

字典的字典

这大致相同,只是更通用。它使用 dict.get 方法,当 dict

中缺少键时,该方法采用默认参数
default_cell = 'D1'
default_sheet = 'Positions'

books = {'Subportfolio 1.xlsm': {'sheet' = 'other_sheet'}, 'Mock Portfolio - He Yibo 2 (TMT).xlsm': {'cell': 'E1'}} #etcetera
for book, book_info in books.items():
    wb = openpyxl.load_workbook(book, keep_vba = True)
    ws = wb.worksheet(book_info.get('sheet', default_sheet))
    message = 'Need to Update %s' % book
    important_cell = book_info.get('cell', default_cell)
    if datetime.datetime.today().weekday() == 6: #check if its sunday
        if ws.cells(important_cell) != "Price on %s" % last_friday: #check to see if date is last friday
            print (message)
    elif ws.cells(important_cell) != "Price on %s" % d: #check to see if date is today
        print (message)

Class

您可以制作一个 MyWorkbookClass 来保存每个工作簿的信息,但这可能有点矫枉过正。 A namedtuple充当一种具有固定成员

的迷你class