我使用此代码查找添加的最后一个csv文件,但我无法找到添加的最后3个文件。我可以删除最后一个文件,然后再找到最大值,但我认为这太长了。你能帮我找个解决办法吗?所有我需要的是找到最后3个csv文件添加到一个目录。
import pandas as pd
import csv
import os
import zipfile
t=[]
j_csvs="path2"
#Find all csv files directories and collect them within t
d = os.path.join(j_csvs)
for root,dirs,files in os.walk(d):
for file in files:
if file.endswith(".csv"):
p=os.path.abspath(os.path.join(root, file))
t.append(p)
else: "DoNothing"
latest_f_j = max(t, key=os.path.getctime)
df=pd.read_csv(latest_f_j)
df
使用sorted
和回调函数来推断排序关系,有以下几种可能性:
- 用
os.path.getctime
设置系统的ctime(它是系统相关的,参见文档) - 用
os.path.getmtime
表示最后修改时间 - 用
os.path.getatime
表示最后一次访问时间。
按降序传递reverse=True
参数,然后切片。
import os.path
def last_newest_files(path, ref_ext='csv', amount=3):
# return files ordered by newest to oldest
def f_conditions(path):
# check by file and extension
_, ext = os.path.splitext(path) # ext start with ".", ie ".csv"
return os.path.isfile(path) and ext.lstrip('.') == ref_ext
# apply conditions
filtered_files = filter(f_conditions, (os.path.join(path, basename) for basename in os.listdir(path)))
# get the newest
return sorted(filtered_files, key=os.path.getctime, reverse=True)[:amount]
path_dir = '.'
ext = 'csv'
last_n_files = 3
print(*last_newest_files(path_dir, ext, last_n_files), sep='n')
您无法确定最后添加的3个文件是什么。
在上层,系统可以按日期、文件类型、大小、名称(区分大小写和不区分大小写)的顺序排列这些文件。
对于日期顺序,您无法知道,因为日期戳可以被操纵,因为可以将日期提前的文件移到目录中,从而保留其原始日期和时间细节。
如果您正在查看较低级别的文件,如文件系统所看到的,那么它们通常是无序的。o/s会根据自己的想法存储它认为合适的细节。
您无法确定3个文件中哪个是最后添加的。好吧,你有一种方法,在目录上运行一个手表,当一个文件被添加时,它会触发,并保持一个3个循环列表,在移动到下一个文件之前替换当前的文件,然后等待下一个触发器触发。