python用时间戳给文件命名规则_Python根据部分名称和文件时间戳读取文本文件

I'm trying to pull two of the same files into python in different dataframes, with the end goal of comparing what was added in the new file and removed from the old. So far, I've got code that looks like this:

In[1] path = r'\\Documents\FileList'

files = os.listdir(path)

In[2] files_txt = [f for f in files if f[-3:] == 'txt']

In[3] for f in files_txt:

data = pd.read_excel(path + r'\\' + f)

df = df.append(data)

I've also set a variable to equal the current date minus a certain number of days, which I want to use to pull the file that has a date equal to that variable:

d7 = dt.datetime.today() - timedelta(7)

As of now, I'm unsure of how to do this, as the first part of the filename always remains the same but they add numbers at the end (eg. file_03232016 then file_03302016). I want to parse through the directory for the beginning part of the filename and add it to a dataframe if it matches the date parameter I set.

EDIT: I forgot to add that sometimes I also need to look at the system date created timestamp, as the text date in the file name isn't always there.

解决方案

Here are some modifications to your original code to get a list of files containing your target date. You need to use strftime.

import os

from datetime import timedelta

d7 = dt.datetime.today() - timedelta(7)

target_date_str = d7.strftime('_%m%d%Y')

files_txt = [f for f in files if f[-13:] == target_date_str + '.txt']

>>> target_date_str + '.txt'

'_03232016.txt'

data = []

for f in files_txt:

data.append(pd.read_excel(os.path.join(path, f))

df = pd.concat(data, ignore_index=True)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值