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

时间:2023-03-09 08:16:15
python获取指定目录下特定格式的文件名

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

 dir *.jpg /b/s > train.set

 pause

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

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

 # -*- coding: utf-8 -*-
"""
Created on Mon Dec 12 14:59:46 2016 @author: shenruixue to calculate size after filter in conv and pool
"""
import os.path, time
import exceptions
import glob
import os class TypeError (Exception):
pass
if __name__ == '__main__':
file_srx = open("train.set")#其中包含所有待计算的文件名
file_object = open('all_time.txt', 'w')
line = file_srx.readline()
diff_time_all = 0
while line:
f = line[:-1] # 除去末尾的换行符
print (f)
print ('***********************************************************')
mtime = time.ctime(os.path.getmtime(f))
ctime = time.ctime(os.path.getctime(f))
mtime_s = (os.path.getmtime(f))
ctime_s = (os.path.getctime(f))
print "Last modified : %s, last created time: %s" % (mtime, ctime)
diff_time = (int(mtime_s) - int(ctime_s))
diff_time_all = diff_time_all + diff_time
print "diff time is ", diff_time f_record = f[:-17] #根据f给f_record进行赋值,需要根据实际情况修改17的大小
print (f_record)
print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*')
os.chdir(f_record)
for file_name in glob.glob("*.jpg"):
print file_name
print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*') file_object.write(file_name + " time is " + str(diff_time) + "\n")
line = file_srx.readline()
print "diff_time_all is ", diff_time_all file_object.write(str(diff_time_all))
file_object.close( )

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

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

 # -*- coding: utf-8 -*-
"""
Created on Mon Dec 12 14:59:46 2016 @author: shenruixue to calculate size after filter in conv and pool
"""
import os.path, time
import exceptions
import glob
import os
rootdir = os.getcwd()
if __name__ == '__main__':
file_object = open('name.set', 'w')
for file_name in glob.glob("*.jpg"):
print file_name
print ('*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*')
file_object.write(rootdir + file_name + "\n")
file_object.close( )