【问题标题】:picking the correct csv file选择正确的 csv 文件
【发布时间】:2019-11-14 14:40:38
【问题描述】:

我是 python 新手。 我希望 python 从文件夹中选择正确的 csv 文件。 我想比较最实际的文件 (t) 和昨天的文件 (t-1) 的 CDS 价差。

因此,代码必须选择今天的文件和昨天的文件。 “昨天的”文件可以是昨天或前天的。

下面的代码标识了文件,但使用代码中的最后日期创建昨天的数据框。

today = dt.date.today()
d1 = today.strftime("%Y%m%d")
print(d1)
t2 = today - timedelta(days = 1) 
t3 = today - timedelta(days = 2) 
t4 = today - timedelta(days = 3) 
t2 = t2.strftime("%Y%m%d")
t3 = t3.strftime("%Y%m%d")
t4 = t4.strftime("%Y%m%d")
print(t2)
print(t3)
print(t4)

if (os.path.exists(path'+d1+'.csv')):
    dataframe2 = pd.read_csv(path'+d1+'.csv')
if (os.path.exists(path-'+t2+'.csv')):
    dataframe2 = pd.read_csv(path'+t2+'.csv')
if (os.path.exists(path'+t3+'.csv')):
    dataframe2 = pd.read_csv(path'+t3+'.csv')
if (os.path.exists(path-'+t4+'.csv')):
    dataframe2 = pd.read_csv(path'+t4+'.csv')

如何告诉python,如果第一个文件退出,建立一个数据框并停止检查以下日期?

【问题讨论】:

    标签: python file csv picking


    【解决方案1】:

    更灵活的方法是使用循环减少日期直到找到文件,然后停止:

    t = dt.date.today()
    d = today.strftime("%Y%m%d")
    max_iter = 100
    found = False
    while max_iter > 0:
        print(d)
        if os.path.exists(path+d+'.csv'):
            found = True
            break
        t = t - timedelta(days = 1)
        d = t.strftime("%Y%m%d")
        max_iter = max_iter - 1
    
    if found:
        dataframe = pd.read_csv(path+d+'.csv')
    else:
        print("No valid file found.")
    

    我还添加了一个计数器max_iter,它限制循环运行的次数,这样即使找不到文件也能完成。

    【讨论】:

    • 非常感谢您的回答!我试试看。
    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多