如何在Python中以X开头搜索文件?

时间:2019-06-15 12:04:09

标签: python python-3.x python-2.7

我有一个脚本,该脚本获取的文件早于X日期,但问题是当我进行某些搜索时,该脚本接收了所有早于X的文件,我只需要指定以Back *开头的文件,而不是所有文件:/

from sys import argv
import os, time

script, dir, age = argv
print "Searching in directory %s for file older than %s day(s)" % (str(argv[1]), str(argv[2]))

#convert age to sec. 1 day = 24*60*60
age = int(age)*86400

for file in os.listdir(dir):
    now = time.time()
    filepath = os.path.join(dir, file)
    modified = os.stat(filepath).st_mtime
    if modified < now - age:
        if os.path.isfile(filepath):
            #print (filepath)
            print 'Result : %s (%s)' % (file, str(argv[2]))

1 个答案:

答案 0 :(得分:0)

您只需要添加一个文件名是否以“ Back”开头的检查,例如:

if (os.path.isfile(filepath)
    and modified < now - age
    and os.path.basename(filepath).startswith("Back")):
  print 'Result : %s (%s)' % (file, str(argv[2]))

或者,如果您不尝试递归搜索目录,则可以将os.path.basename(filepath)替换为file