【问题标题】:Python merging files in directoryPython合并目录中的文件
【发布时间】:2018-10-26 11:39:23
【问题描述】:

我在具有这种模式 YYYY/MM/DD/HH/MM 的目录中有数千个文件:

  • 201801010000.txt
  • 201801010001.txt
  • 201801010002.txt

我只想保留小时数,因此我需要将每天每小时的 60 个文件合并为一个。 我不知道如何搜索文件名以获取我想要的 60 个文件。这是我写的

def concat_files(path):
    file_list = os.listdir(path)
    with open(datetime.datetime.now(), "w") as outfile:
        for filename in sorted(file_list):
            with open(filename, "r") as infile:
                outfile.write(infile.read())

如何命名文件以保留日期?我现在正在使用日期时间,但它会覆盖当前文件名。使用我的代码,我将所有文件合并为一个,我应该将每个 % 60 合并到一个不同的文件中。

【问题讨论】:

  • 如果文件名已经是 YYMMDDHHMM 格式,你就不能把.txt扩展名前的最后两个字符去掉吗?
  • IMO groupbydatetime.strptime 的组合将轻松解决此问题。你能详细说明输入和输出吗?

标签: python file merge concatenation cat


【解决方案1】:

你没那么远,你只需要交换你的逻辑:

file_list = os.listdir(path)
for filename in sorted(file_list):
    out_filename = filename[:-6] + '.txt'
    with open(out_filename, 'a') as outfile:
        with open(path + '/' + filename, 'r') as infile:
            outfile.write(infile.read())

【讨论】:

    【解决方案2】:

    您可以使用glob 来获取您想要的文件。它允许您在搜索文件时传入要匹配的模式。在下面的最后一行,它只会找到以'2018010100' 开头,有两个字符,并以'.txt' 结尾的文件

    from glob import glob
    
    def concat_files(dir_path, file_pattern):
        file_list = glob(os.path.join(dir_path, file_pattern))
        with open(datetime.datetime.now(), "w") as outfile:
            for filename in sorted(file_list):
                with open(filename, "r") as infile:
                    outfile.write(infile.read())
    
    concat_files('C:/path/to/directory', '2018010100??.txt')
    

    【讨论】:

      【解决方案3】:

      试试这个。

      file_list = os.listdir(path)
      for f in { f[:-6] for f in file_list }:
          if not f:
              continue
          with open(f + '.txt', 'a') as outfile:
              for file in sorted([ s for s in file_list if s.startswith(f)]):
                  with open(path + '/' + file, 'r') as infile:
                      outfile.write(infile.read())
                  #os.remove(path + '/' + file) # optional
      

      【讨论】:

      • 欢迎来到 Stack Overflow!虽然很高兴回答问题并且我们欢迎它,但也有必要解释您的代码作为解决方案做了什么。将相关解释添加到您的答案中。 From Review
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多