捕获Python中过去x天内修改过的文件

时间:2016-09-26 17:15:48

标签: python handbrake

我使用以下脚本使用HandBrake CLI将现有媒体文件重新编码为MP4。这将是一个漫长的过程,因此我想要一种方法来捕获过去7天内创建的文件,以及其他过滤器(文件扩展名),以便可以更新新内容,而旧内容可以在不同时间在单独的脚本上运行。我必须在脚本中更改为仅捕获过去7天内创建的文件?

import os
import time
import subprocess
import sys
import httplib
import urllib
from xml.dom import minidom
import logging
import datetime

#Script Directory setup
myDateTime = datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
logdir = 'D:\\logs\\'
logfile = logdir + 'TV_encode-' + myDateTime + '.log'

#Log Handler Setup
logger = logging.getLogger('TV_encode')
hdlr = logging.FileHandler(logfile)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

logger.info('Getting list of files to re-encode...')
fileList = []
rootdir = 'T:\\'
logger.info('Using %s as root directory for scan...' % rootdir)
for root, subFolders, files in os.walk(rootdir):
    for file in files:
        theFile = os.path.join(root,file)
        fileName, fileExtension = os.path.splitext(theFile)
        if fileExtension.lower() in ('.avi', '.divx', '.flv', '.m4v', '.mkv', '.mov', '.mpg', '.mpeg', '.wmv'):
            print 'Adding',theFile
            logger.info('Adding %s to list of file to re-encode.' % theFile)
            fileList.append(theFile)

runstr = '"C:\\Program Files\\Handbrake\\HandBrakeCLI.exe" -i "{0}" -o "{1}" --preset="Normal" --two-pass --turbo'

print '=======--------======='
logger.info('=======--------=======')
logger.info('Starting processing of files...')

while fileList:
    inFile = fileList.pop()
    logger.info('Original file: %s' % inFile)
    fileName, fileExtension = os.path.splitext(inFile)
    outFile = fileName+'.mp4'
    logger.info('New file: %s' % outFile)

    print 'Processing',inFile
    logger.info('Processing %s' % inFile)
    returncode  = subprocess.call(runstr.format(inFile,outFile))
    time.sleep(5)
    print 'Removing',inFile
    logger.info('Removing %s' % inFile)
    os.remove(inFile)

    logger.info('Sending Pushover notification...')
    conn = httplib.HTTPSConnection("api.pushover.net:443")
    conn.request("POST", "/1/messages.json",
                 urllib.urlencode({
                     "token": "TOKENHERE",
                     "user": "USERKEY",
                     "message": "Re-encoding complete for %s" % fileName,
                 }), {"Content-type": "application/x-www-form-urlencoded"})
    conn.getresponse()

1 个答案:

答案 0 :(得分:1)

os.path.getmtime(filename)将为您提供自纪元以来的修改时间。

使用datetime模块将其转换为datetime对象,并照常比较。

import datetime
import os

ONE_WEEK_AGO = datetime.datetime.today() - datetime.timedelta(days=7)

mod_date = datetime.datetime.fromtimestamp(os.path.getmtime(theFile))
if mod_date > ONE_WEEK_AGO:
    # use the file.