【问题标题】:how to run multiple text files as input in Python如何在 Python 中运行多个文本文件作为输入
【发布时间】:2020-12-13 16:08:43
【问题描述】:

我编写了一个 python 代码,它将输入一个 txt 文件并打印到 excel 。我能够实现一个 txt 文件作为输入。但是我的要求是在一个文件夹中有大约一百万个 txt 文件。所以我不知道如何更改 python 代码以从文件夹中获取输入。

以下代码处理输入 1.txt 文件。我想从一个文件夹中运行多个 txt 文件,这是我的要求。

with open('C:/test/1.txt') as infile:
    registrations = []
    fields = OrderedDict()
    d = {}
    for line in infile:
        line = line.strip()
        if line:
            key, value = [s.strip() for s in line.split(':', 1)]
            d[key] = value
            fields[key] = None
        else:
            if d:
                registrations.append(d)
                print(d)
                d = {}
                if ',' not in line:
                    print('line without ,:', line)
                    continue
    else:
        if d:    # handle EOF
            registrations.append(d)

with open('C:/registrations.csv', 'w') as outfile:
    writer = DictWriter(outfile, fieldnames=fields)
    writer.writeheader()
    writer.writerows(registrations)

谢谢, 米拉

【问题讨论】:

    标签: python parsing text


    【解决方案1】:

    使用 pathlib 模块:

    from pathlib import Path
    
    
    FOLDER = Path('your/folder/here')
    
    for file in FOLDER.glob('*.txt'):
        # Do your thing
        pass
    

    【讨论】:

      【解决方案2】:

      根据您的源代码,我对其进行了优化。我使用os.walk 访问每个 .txt 文件,然后在这些 txt 文件中逐行读取并将其保存在枚举中。然后我将检查该枚举中的每一行。

      import os
      
      extension = [".txt"]
      path = "C:/test"
      for subdir, dirs, files in os.walk(path):
          for file in files:
              file_path = os.path.join(subdir, file)
              ext = os.path.splitext(file)[-1].lower()       
              if ext in extension:
                  with open(file_path, "r") as f:
                      try:
                          f_content = f.readlines()
                      except Exception as e:
                          print(e)
                  for l_idx, line in enumerate(f_content):
                  # ..................................
      
      # l_idx: return position line
      # line: content in line
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多