情况:a文件夹下有b,c,d等若干文件夹,b,c,d等文件夹下又各自有若干csv文件。
需求:需要找到b,c,d等文件夹中最新和次新的两个文件进行比较,然后将所有的增量汇总。
那么问题来了,到底怎么取最新和次新的文件?python支持吗?
1 Python获取文件最新的修改时间
# 方法一
import os
def listdir(path, list_name):
"""
将文件路径和修改时间存入列表中
:param path: 文件夹的绝对路径
:param list_name: 空列表
:return:
"""
for file in os.listdir(path): # 对目录中的所有文件进行遍历
file_path = os.path.join(path, file) # 文件的路径
if os.path.isdir(file_path): # 如果拼接后的还是目录,进行递归
listdir(file_path, list_name)
else: # 如果拼接之后,还是文件,就将元组形式存到列表
list_name.append((file_path, os.path.getmtime(file_path)))
def newestfile(target_list):
"""
找出最新修改的文件
:param target_list: 存有文件路径和修改时间的列表
:return: 最新的文件
"""
newest_file = target_list[0] # 默认第一个元组中的文件是最新的
for i in range(len(target_list)): # 对列表进行遍历
if i < (len(target_list) - 1) and newest_file[1] < target_list[i + 1][1]:
newest_file = target_list[i + 1]
else:
continue
print('newest file is', newest_file)
return newest_file
p = r'G:\test_demo'
list = []
listdir(p, list)
new_file = newestfile(list)
# 方法二
def new_report(test_report):
lists = os.listdir(test_report) # 列出目录的下所有文件和文件夹保存到lists
lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn)) # 按时间排序
file_new = os.path.join(test_report, lists[-1]) # 获取最新的文件保存到file_new
return file_new
file_new = new_report("G:\\test_demo")
print(file_new)
2 比对csv文件
import csv
with open('a.csv') as f:
reader = csv.reader(f)
# print(list(reader))
# input()
als = list(reader)
with open('b.csv') as f:
reader = csv.reader(f)
# print(list(reader))
bls = list(reader)
bdict = {}
for b in bls[1:]:
if b[2] == '':
continue
bdict[b[2]] = [b[i] for i in [1]+list(range(4, 13))]
adict = {}
for a in als[1:]:
adict[a[10]] = [a[i] for i in [9]+list(range(11, 20))]
for a in als[1:]:
a_ls = adict[a[10]]
b_ls = bdict[a[10]]
b_wrong = False
for i in range(len(a_ls)):
if i in [1, 8]:
if b_ls[i] not in a_ls[i]:
b_wrong = True
a_str = a_ls[i]
b_str = b_ls[i]
else:
if b_ls[i] != a_ls[i]:
b_wrong = True
a_str = a_ls[i]
b_str = b_ls[i]
if b_wrong:
print('%s的%s和%s不一致'%(a[10], a_str, b_str))
break
```