我是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)")
答案 0 :(得分:1)
这第一部分确实不是非常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)
另一种改进方法是用dict或namedtuples替换所有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)
你可以创建一个MyWorkbookClass来保存每个工作簿的信息,但这可能是过度的。 namedtuple
充当一种具有固定成员的小型班级
答案 1 :(得分:0)
我没有使用过该模块,但这是我所知道的另一种方法:
假设您的工作簿位于同一文件夹中,您可以使用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
并按名称打开所需的工作簿。当然,索引的赋值与本模块中的函数不同。