根据日期范围合并文件
Combining files based on a date range
我对脚本编写还很陌生,因此我不确定如何最好地合并一系列文件。我正在尝试创建一个质量控制脚本,以确保每晚的负载已正确上传到数据库(我们注意到,如果由于某种原因存在延迟,同步将排除在所述延迟期间收到的任何捐赠)。
我有一个每日同步文件目录,标记如下:
20161031_donations.txt
20161030_donations.txt
20161029_donations.txt
20161028_donations.txt
etc etc
每个文件都有相同的header。
我想将最近 7 天的文件合并到一个只有 1 header 行的文件中。我主要是在努力理解如何通配日期范围。我只做过:
for i in a.txt b.txt c.txt d.txt
do this
done
这对于静态合并来说很好,但不能动态地集成到适当的 QC 脚本中。
我有 unix 背景,但想在 python 中进行此操作。我是 python 的新手,所以请在任何建议中进行解释。
日期格式的优点(假设它有零填充,例如 20160203
表示 2 月 3 日)是可以按字母顺序排序!所以你可以这样做:
from glob import glob
for path in sorted(glob('*_donations.txt'))[-7:]:
with open(path) as f:
# get the content for merging
这将获取 7 个最新的文件,从最早的开始。 This is why ISO 8601 is the best date format.
扩展 Alex Hall 的回答,您可以从一个文件中获取 header 并跳过它以对其余文件进行合并
from glob import glob
from shutil import copyfileobj
files = sorted(glob('*_donations.txt'))[-7:]
# if you want most recent file first do
# files.reverse()
with open("merged_file.txt", "w") as outfp:
for i, filename in enumerate(files):
with open(filename) as infile:
if i:
next(infile) # discard header
copyfileobj(infile, outfile) # write remaining
我对脚本编写还很陌生,因此我不确定如何最好地合并一系列文件。我正在尝试创建一个质量控制脚本,以确保每晚的负载已正确上传到数据库(我们注意到,如果由于某种原因存在延迟,同步将排除在所述延迟期间收到的任何捐赠)。
我有一个每日同步文件目录,标记如下:
20161031_donations.txt
20161030_donations.txt
20161029_donations.txt
20161028_donations.txt
etc etc
每个文件都有相同的header。
我想将最近 7 天的文件合并到一个只有 1 header 行的文件中。我主要是在努力理解如何通配日期范围。我只做过:
for i in a.txt b.txt c.txt d.txt
do this
done
这对于静态合并来说很好,但不能动态地集成到适当的 QC 脚本中。
我有 unix 背景,但想在 python 中进行此操作。我是 python 的新手,所以请在任何建议中进行解释。
日期格式的优点(假设它有零填充,例如 20160203
表示 2 月 3 日)是可以按字母顺序排序!所以你可以这样做:
from glob import glob
for path in sorted(glob('*_donations.txt'))[-7:]:
with open(path) as f:
# get the content for merging
这将获取 7 个最新的文件,从最早的开始。 This is why ISO 8601 is the best date format.
扩展 Alex Hall 的回答,您可以从一个文件中获取 header 并跳过它以对其余文件进行合并
from glob import glob
from shutil import copyfileobj
files = sorted(glob('*_donations.txt'))[-7:]
# if you want most recent file first do
# files.reverse()
with open("merged_file.txt", "w") as outfp:
for i, filename in enumerate(files):
with open(filename) as infile:
if i:
next(infile) # discard header
copyfileobj(infile, outfile) # write remaining