【问题标题】:Python - name output file to include part of input file namePython - 命名输出文件以包含输入文件名的一部分
【发布时间】: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


【解决方案1】:

time.strptime可以解析你想要的任何时间格式,time.strftime可以生成你想要的任何时间格式。您应该阅读(并可能解析)所有这些,并使用min(...)max(...) 来获得最小和最大。

例如,如果文件名看起来像 foo2014-06-16bar.txthello2014-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

【讨论】:

  • 有 n 个文件,所以我不能这样写出来。我需要一种方法来遍历文件名并提取最早的定时文件名和最新的定时文件名并从文件名中提取时间
  • 首先构建n 文件的files 列表,然后才执行问题中的操作有什么问题?一旦你有了files 列表,你就可以遍历它,你不必再次扫描文件系统。
  • 我试过 os.listdir 但它不起作用。我无法输入 145 个文件的名称。这段代码需要能够遍历我给它的任何文件目录,而不仅仅是我现在正在查看的特定文件
  • os.listdir 和 os.walk 都可以正常工作。如果它们对您不起作用,并且您无法单独解决,请再问 StackOverflow 的问题。
  • 我们显然是误会了。我问这个问题是为了获得帮助。关键是我需要帮助格式化一个允许我使用这样的代码的循环。我的代码不能特定于某些文件。我需要能够为我选择的任何目录运行它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多