【发布时间】:2014-05-12 19:18:48
【问题描述】:
给定一个包含大量小文件 (>1 mio) 的目录,有什么方法可以快速记住哪些文件已被处理(用于数据库导入)。
我尝试的第一个解决方案是 bash 脚本:
#find all gz files
for f in $(find $rawdatapath -name '*.gz'); do
filename=`basename $f`
#check whether the filename is already contained in the process list
onlist=`grep $filename $processed_files`
if [[ -z $onlist ]]
then
echo "processing, new: $filename"
#unzip file and import into mongodb
#write filename into processed list
echo $filename #>> $processed_files
fi
done
对于较小的样本(160k 文件),这运行了大约 8 分钟(没有任何处理)
接下来我尝试了一个python脚本:
import os
path = "/home/b2blogin/webapps/mongodb/rawdata/segment_slideproof_testing"
processed_files_file = os.path.join(path,"processed_files.txt")
processed_files = [line.strip() for line in open(processed_files_file)]
with open(processed_files_file, "a") as pff:
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".gz"):
if file not in processed_files:
pff.write("%s\n" % file)
这运行不到 2 分钟。
我忽略了一种明显更快的方法吗?
其他解决方案:
- 由于我使用 s3sync 下载新文件,将处理后的文件移动到不同的位置并不方便
- 由于文件名称中包含时间戳,我可能会考虑依赖按顺序处理它们,并且仅将名称与“最后处理”日期进行比较
- 或者,我可以跟踪上次运行处理的时间,并且只处理此后修改过的文件。
【问题讨论】:
-
跟踪时间可能是最快的