简体   繁体   English

使用 Python 获取知道其特定名称/字符串的文件

[英]Get file knowing its specific name/string using Python

I would like to get the excel file whose name ends with"_updated" string in my current working directory.我想在我当前的工作目录中获取名称以“_updated”字符串结尾的 excel 文件。 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).但是,由于我有 3 个xlsx文件,下面的代码输出打印语句 3 次(应该只有一次)。 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".我想使用“filename_updated.xlsx”使用openpyxl库进行进一步处理,加载文件“filename_updated.xlsx”的整个工作簿的代码如下所示,其中data_file将包含名称的所有文件以“_updated.xlsx”结尾。 Not sure what am I doing wrong ?不知道我做错了什么? I am pretty sure will be minor.我很确定会是次要的。

Thanks in advance for your time!在此先感谢您的时间!

Python code: Python代码:

import os
import glob

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

Openpyxl code打开pyxl代码

wb = load_workbook(data_file)

Updated code after SO User Comment SO用户评论后更新代码

path = Path(os.getcwd())

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

I'am not sure what the os.listdir() is supposed to do, but i think this code will do what you want.我不确定os.listdir()应该做什么,但我认为这段代码会做你想做的。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM