【问题标题】:Python select last 12 hours new generated files in a folderPython选择文件夹中最近12小时新生成的文件
【发布时间】:2021-07-26 06:08:09
【问题描述】:

我正在尝试获取过去 12 小时内的所有文件,文件名和列表格式如下:

C:\myproject\Attendance_aaa_2021-07-22-4hr.csv     07/22/2021 04:20 AM Modified
C:\myproject\Attendance_bbb_2021-07-23-16hr.csv    07/23/2021 16:20 PM Modified
C:\myproject\Attendance_ccc_2021-07-26-4hr.csv     07/26/2021 04:15 AM Modified
C:\myproject\Attendance_ddd_2021-07-26-16h.csv     07/26/2021 16:15 AM Modified
C:\myproject\Attendance_eee_2021-07-26-16h.csv     07/26/2021 16:35 AM Modified

这是我的代码:

import os
path_dataset = r'C:\myproject\'

def get_file(path_dataset):
     files = os.listdir(path_dataset) #check file list
     files.sort() #sort file
     file_list = []
     for file in files:
         if (file.startswith("Attendance")) & (file.endswith(".csv")):
              f_name = str(file) 
              tr = '\\'
              filename = path_dataset + tr + f_name
              file_list.append(filename)
                  
     return (file_list)


get_file(path_dataset)

但是,此代码将返回文件夹中的所有文件。我正在考虑使用以下代码来识别文件修改时间:

last12HourDateTime = datetime.today() - timedelta(hours = 12)

因此,从现在起过去 12 小时内的所有文件都将列在我的 file_list 中。 有人可以帮忙吗,如何整合文件列表的时间排序?非常感谢!

【问题讨论】:

  • os.path.getmtime(path) 为您提供该文件的修改时间。
  • Python 布尔“和”运算符是单词and,而不是符号&

标签: python sorting recent-file-list


【解决方案1】:
import os
import time
path_dataset = 'C:\\myproject\\'
twelve = time.time() - 12 * 60 * 60

def get_file(path_dataset):
     files = os.listdir(path_dataset) #check file list
     file_list = []
     for file in files:
         path = path.dataset + "\\" + file
         if file.startswith("Attendance") and file.endswith(".csv") and os.path.getmtime(path) > twelve:
              file_list.append(path)
     return file_list

print(get_file(path_dataset))

【讨论】:

  • 谢谢蒂姆!但是,我尝试过,您的代码仍然选择所有文件。顺便说一句,我必须修改 os.path.getmtime()。一个小错误。
  • 我把不等式倒过来了。您希望文件修改时间少于 12 小时。
  • 谢谢蒂姆!终于解决了我的问题!请注意编辑 os.path.getmtime() 以改进答案。
  • 有趣;我在发布后不久就修复了它。我一定是忘记保存了。
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
相关资源
最近更新 更多