简体   繁体   English

读取文件夹中具有特定字符串名称的最新文件

[英]Read the latest file in the folder with a specific string name

I need to open the latest file that was created with a specific string in its name.我需要打开在其名称中使用特定字符串创建的最新文件。 There are two files generated every 10 minutes in the folder from the database, one of them with string "XXX" and another one with "YYY".数据库中的文件夹中每 10 分钟生成两个文件,一个带有字符串“XXX”,另一个带有“YYY”。 I need to open the latest file with "XXX".我需要用“XXX”打开最新的文件。 My current code takes a little bit more time then I was expecting, about 45 sec, and I was wondering whether somebody could suggest me how to improve it to run faster.我当前的代码比我预期的要多一点时间,大约 45 秒,我想知道是否有人可以建议我如何改进它以更快地运行。

Here is my code:这是我的代码:

from datetime import datetime
import pandas as pd
today_str = datetime.date.today().strftime('%m%d%Y')
x_in_strng = ["XXX"]
dt_lst = [today_str]
file_lst = []
path = "xx/xxxx/xxxx"

list_of_files = glob.glob(path + '*') 
for filename in list_of_files:
    if all(x not in filename for x in x_in_strng) and all(x in filename for x in dt_lst):
        file_lst.append(filename)
        latest_file = max(file_lst, key=os.path.getctime)
        data_df = pd.read_csv(latest_file)
        

You may find this faster:你可能会发现这个更快:

from glob import glob, escape
import os
import pandas as pd

def get_latest_file(directory, pattern):
    glob_pattern = os.path.join(directory, f'*{pattern}*')
    ctime = float('-inf')
    file = None
    for filename in glob(glob_pattern):
        if (ct := os.path.getctime(filename)) > ctime:
            ctime = ct
            file = filename
    if file is not None:
        return pd.read_csv(file)

df = get_latest_file('basedir', 'XXX')

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

相关问题 (python) 读取文件夹中特定类型的.xlsx 文件名 - (python) read specific type of .xlsx file name in a folder Python:提供一个字符串,打开文件夹名称中包含字符串的文件夹,然后打开/读取该文件夹中的文件 - Python: Provide a string, open folder that contains the string in the folder name, then open/read a file in that folder 如何使用python获取最新创建的文件名而不是文件夹名? - How to get the latest created file name and not the folder name using python? 读取文件名包含python中的字符串的最新文件 - Read latest file with a filename contains string in python 如何读取文件夹名称并将结果输出到字符串 - How to read a folder name and output result to a string 如何获取文件夹中没有路径的最新文件名? - How to get the latest file name without path in a folder? 检查是否存在名称以特定字符串开头的文件夹 - checking if there is a folder with a name that start with a specific string 如何使用已定义的字符串但变量后缀 python 读取文件路径或文件夹名称 - How to read to a file path or folder name with a defined string but variable suffix python 如何从特定文件夹中读取图像名称? - How can I read image name from a specific folder? 将许多 csvs 的文件夹读入字典,每个字典的名称都是文件名 - Read folder of many csvs into dictionaries each with their name being the file name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM