【问题标题】:Read a csv file with its name changing daily读取名称每天更改的 csv 文件
【发布时间】:2020-07-11 02:08:46
【问题描述】:

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

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

Name_29Mar2020_data_by_company.csv

明天的文件是:

Name_30Mar2020_data_by_company.csv

【问题讨论】:

  • 您可以使用datetime 模块中的strftime 函数将日期解释为str 对象以更新您的文件名参数。尝试一下并将您的尝试更新为问题。

标签: python pandas csv automation filenames


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      相关资源
      最近更新 更多