Home > Software engineering >  Get file knowing its specific name/string using Python
Get file knowing its specific name/string using Python

Time:05-30

I would like to get the excel file whose name ends with"_updated" string in my current working directory. For this I am running below code. However, since I have 3 xlsx file, below code is outputting the print statement 3 times (should be only one time). I would like to use the "filename_updated.xlsx" for further processing using openpyxl library, and the code for loading the entire workbook for the file "filename_updated.xlsx" will look like below, where data_file will contain will contain all the files whose name ends with "_updated.xlsx". Not sure what am I doing wrong ? I am pretty sure will be minor.

Thanks in advance for your time!

Python code:

import os
import glob

for filename in os.listdir():
    for filename1 in glob.glob(" path\\*_updated.xlsx"):
        print(filename1)

Openpyxl code

wb = load_workbook(data_file)

Updated code after SO User Comment

path = Path(os.getcwd())

wbs = []
for filename in path.glob("*_updated.xlsx"):
    wbs.append(load_workbook(filename))
    wb = load_workbook(filename)

CodePudding user response:

I'am not sure what the os.listdir() is supposed to do, but i think this code will do what you want.

from pathlib import Path
from openpyxl import load_workbook

path = Path("your path")

wbs = []
for filename in path.glob("*_updated.xlsx"):
    wbs.append(load_workbook(filename))
  • Related