【发布时间】:2014-08-07 23:15:27
【问题描述】:
我正在使用 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的输出文件
如何调整此代码以进行我之前所说的更改?
【问题讨论】:
-
您可以使用
re模块和(可选)time.strptime来解析输入文件名中的日期。得到输出文件名后,可以直接打开写入,或者写入outputfile.pkt后重命名。 -
时间是否必须采用特定格式才能这样做?另外,我将如何确保我第一次和最后一次使用这种方法。真的,我只需要获取文件名的大块并将其设置为新的输出文件名。
-
你能提供一些示例文件名吗?
-
Data_d20140526_t2359590_Data.h5 是输入文件的示例。 Data_d20140526_t2359590_d20140527_t0019590.pkt 是输出文件的样子,其中 d20140526_t2359590 是第一次输入文件的文件名中包含的日期和时间,d20140527_t0019590 是最后一次输入文件名中包含的日期和时间
标签: python numpy path filenames python-2.6