Python - 输出文件名包含输入文件名的一部分
我正在使用 Python 2.6。
我输入了 n
个文件,并通过循环处理这些文件中的数据,然后把处理后的信息输出到一个单独的文件里。
这些输入文件的命名格式是 inputfile_date_time.h5
,每个文件的日期和时间都不一样。
我想把输出文件命名为 outputfile_firstdate_firsttime_lastdate_lasttime.pkt
,其中 firstdate_firsttime
是输入文件中最早的日期和时间(也就是在这 n
个文件中,名字最先出现的那个文件的日期和时间),而 lastdate_lasttime
是输入文件中最晚的日期和时间(也就是在这 n
个文件中,名字最后出现的那个文件的日期和时间)。
我现在的代码是这样的:
import os
from glob import glob
from os.path import basename
import numpy
import hdf5
#set location/directory of input files
inputdir = "/Location of directory that contains files"
#create output file
outputfilename = 'outputfilename'
outputfile = "/Location to put output file/"+basename(outputfilename)[:-4]+".pkt"
ofile = open(outputfile, 'wb')
for path, dirs, files in os.walk(inputdir):
files_list = glob(os.path.join(inputdir, '*.h5'))
for file in files_list:
f = h5py.File(os.path.join(files_list,file), 'r')
f.close()
#for loop performing the necessary task to the information in the files
#print that the output file was written
print "Wrote " + outputfile
#close output file
ofile.close()
这段代码创建了一个叫 outputfile.pkt
的输出文件。
我该如何调整这段代码,以实现我之前提到的更改呢?
1 个回答
0
time.strptime
可以解析你想要的任何时间格式,而 time.strftime
则可以生成你想要的任何时间格式。你应该查看(并可能解析)所有这些格式,然后使用 min(...)
和 max(...)
来找出最小和最大的时间。
举个例子,如果文件名看起来像 foo2014-06-16bar.txt
和 hello2014-06-17world
,那么你可以这样解析它们:
import re
files = ['foo2014-06-16bar.txt', 'hello2014-06-17world'
dates = [re.search(r'(?:19|20)\d{2}-\d{2}-\d{2}', f).group() for f in files]
print min(dates) #: 2014-06-16
print max(dates) #: 2014-06-17
接下来,使用 os.walk
来构建 files
的方法如下:
import os
inputdir = "/Location of directory that contains files"
files = []
for dirpath, dirnames, filenames in os.walk(inputdir):
for filename in filenames:
if filename.endswith('.h5'):
pathname = os.path.join(dirpath, filename)
files.append(pathname)
print files