• python获取指定目录下特定格式的文件名


    之前一直用windows下的bat脚本获取一个目录下的指定格式的文件名,如下所示:

    1 dir *.jpg /b/s > train.set
    2 
    3 pause

    十分简单,将这个bat文件放到你想要获取文件名的目录下,然后双击运行就可以将你想要保存的文件名写在train.set文件之中了。

    今天由于实际需求,这个功能需要用python来实现,在网上查了一下发现,python脚本实现起来也很方便,而且也比较灵活,如下所示:

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Mon Dec 12 14:59:46 2016
     4 
     5 @author: shenruixue
     6 
     7 to calculate size after filter in conv and pool
     8 """
     9 import os.path, time
    10 import exceptions
    11 import glob
    12 import os
    13 
    14 
    15 class TypeError (Exception):
    16   pass
    17 if __name__ == '__main__':
    18  file_srx = open("train.set")#其中包含所有待计算的文件名
    19  file_object = open('all_time.txt', 'w')
    20  line = file_srx.readline()
    21  diff_time_all = 0
    22  while line:
    23   f = line[:-1]    # 除去末尾的换行符
    24   print (f)
    25   print ('***********************************************************')
    26   mtime = time.ctime(os.path.getmtime(f))
    27   ctime = time.ctime(os.path.getctime(f))
    28   mtime_s = (os.path.getmtime(f))
    29   ctime_s = (os.path.getctime(f))
    30   print "Last modified : %s, last created time: %s" % (mtime, ctime)
    31   diff_time = (int(mtime_s) - int(ctime_s))
    32   diff_time_all = diff_time_all + diff_time
    33   print "diff time is ", diff_time
    34   
    35   f_record = f[:-17] #根据f给f_record进行赋值,需要根据实际情况修改17的大小
    36   print (f_record)
    37   print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*')
    38   os.chdir(f_record) 
    39   for file_name in glob.glob("*.jpg"):
    40    print file_name
    41    print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*')
    42   
    43   file_object.write(file_name + " time is " + str(diff_time) + "
    ")
    44   line = file_srx.readline() 
    45  print "diff_time_all is ", diff_time_all
    46  
    47  file_object.write(str(diff_time_all))
    48  file_object.close( )

    可以看到用到了os与glog两个包,很方便快捷。

    可以写成一个小脚本,以后方便使用。如下:

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Mon Dec 12 14:59:46 2016
     4 
     5 @author: shenruixue
     6 
     7 to calculate size after filter in conv and pool
     8 """
     9 import os.path, time
    10 import exceptions
    11 import glob
    12 import os
    13 rootdir = os.getcwd()
    14 if __name__ == '__main__':
    15   file_object = open('name.set', 'w')
    16   for file_name in glob.glob("*.jpg"):
    17    print file_name
    18    print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*')
    19    file_object.write(rootdir + file_name + "
    ")
    20   file_object.close( )
  • 相关阅读:
    IISManager 的启动
    基于hadoop集群的hive 安装(mysql,derby)
    Struts中央控制器
    在Spring中配置Hibernate事务
    java 实现多线程下载
    hello,博客园
    easyui datagrid中添加右键菜单事件
    C#项目打包
    easyui datagrid中单击添加菜单事件
    SQL多条件查询拼接in中条件方法
  • 原文地址:https://www.cnblogs.com/rainsoul/p/6277938.html
Copyright © 2020-2023  润新知