[英]How to read excel with starting filename using openpyxl
I have to read excel file with starting file name.我必须读取带有起始文件名的 excel 文件。 So I use glob which return me the file path with file name in list.
所以我使用 glob 返回列表中文件名的文件路径。 Now I want to pass the file path to Openpyxl so I can read excel. How can I do that?
现在我想将文件路径传递给 Openpyxl,这样我就可以读取 excel。我该怎么做?
p= Path(folder location where excel file is saved)
filelist = [x for x in p.glob("**/*.xlsx") if x.name.startswith("PG")]
Output: Output:
[WindowsPath('C:/Users/XXX/Desktop/TEST/2022/05-01-2022/Spectra,/PG+_380806.xlsx')]
I tried to get value from list using for loop because it's window path, I am getting error windows path not iterable.我尝试使用 for 循环从列表中获取值,因为它是 window 路径,我收到错误 windows 路径不可迭代。
The load_workbook() function will accept a WindowsPath as an arugment. load_workbook() function 将接受 WindowsPath 作为参数。
Try something like this:尝试这样的事情:
from openpyxl import load_workbook
from pathlib import Path
p = Path('data')
filelist = [x for x in p.glob("**/*.xlsx") if x.name.startswith("PG")]
for f in filelist:
wb = load_workbook(f)
ws = wb.active
print(f"cols={ws.max_column} rows={ws.max_row}")
# do something with the worksheet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.