读取每天更改名称的 csv 文件

Read a csv file with its name changing daily

我正在尝试读取 Pandas 中的 csv 文件。我正在自动化脚本以每天从 csv 读取数据并执行。 每天都会在我有 csv 文件的文件夹中添加一个新的 csv。新添加的 csv 文件具有相同的名称格式,只是其中的日期部分每天更改,月份部分每月更改。年份每年都会变化。我如何每天自动读取名称不断变化的 csv 文件?

示例: 如果昨天文件的名称是:

Name_29Mar2020_data_by_company.csv

明天的文件是:

Name_30Mar2020_data_by_company.csv

您可以使用日期时间模块:

import pandas as pd
from datetime import datetime

fname = datetime.today().strftime('Name_%d%b%Y_data_by_company.csv')
df = pd.read_csv(fname)

这是我遇到的一个问题,最终我放弃了文件名,因为它们不一致,而是创建了一个函数来根据最新修改时间或创建时间获取最新文件。

from pathlib import Path

def get_latest_file(src_path,extension,method='st_mtime'):
    """ 
    Takes in a raw path and extension to parse over
    returns a single file with the last modified date

    methods:
    st_mtime: It represents the time of most recent content modification. It is 
    expressed in seconds.
    st_ctime: It represents the time of most recent metadata change on Unix 
    and creation time on Windows. It is expressed in seconds.
    """

    extension = extension if extension[0] != '.' else extension[1:]

    files = (Path(src_path).glob(f'*.{extension}'))

    if method == 'st_mtime':
        file_dictionary = {file : file.stat().st_mtime for file in files}
    elif method == 'st_ctime':
        file_dictionary = {file : file.stat().st_ctime for file in files}
    else:
        raise Exception(f'{method} not valid for this function')

    max_file = max(file_dictionary, key=file_dictionary.get)


    return max_file

latest = get_latest_file('C:/Users/DataNovice',extension='csv',method='st_mtime')

print(latest)

out : WindowsPath('C:/Users/DataNovice/new_file_i_just_created.csv')


df = pd.read_csv(latest)