文章内容旨在记录自己根据各位大佬发表的文章,改写的些许实用代码(仅对于初学者)。
一、根据时间处理文件
本次程序针对于目录下文件根据时间排序,进进行处理(复制到指定目录)
1、日常读取目录下所有文件+目录名称
if (os.path.exists(images_path)):
files = os.listdir(images_path)
此处 files 为文件名称列表,包括文件和该目录下以及目录。获取单个文件名可使用for循环。
2、将文件名称按照时间排序
files.sort(key=lambda fn: os.path.getmtime(images_path + "/" + fn)) # 按时间排序
file_new_list = files[::-1] # 倒着取
3、处理得到的按照时间排序的文件
for fil in file_new_list:
if os.path.isfile(os.path.join(images_path, fil)):
shutil.copy(os.path.join(images_path, fil), os.path.join(Outputpath,'1'))
4、完整代码
def get_by_time(images_path, Outputpath):
if (os.path.exists(images_path)):
files = os.listdir(images_path)
files.sort(key=lambda fn: os.path.getmtime(images_path + "/" + fn)) # 按时间排序
file_new_list = files[::-1]
for fil in file_new_list:
if os.path.isfile(os.path.join(images_path, fil)):
shutil.copy(os.path.join(images_path, fil), os.path.join(Outputpath,'1'))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--images_path', required=True, help='Folder with images')
parser.add_argument('-o', '--Outputpath', required=True, help='Folder with Output ')
args = parser.parse_args()
get_by_time(args.images_path, args.Outputpath)