【问题标题】:How to process multiple files based on their names?如何根据名称处理多个文件?
【发布时间】:2021-03-20 17:47:48
【问题描述】:

使用下面的代码,我从多个目录中收集文件。我检查他们的日期,检查他们是否存在于列表missing_dates 中,并检查该特定日期是否存在于每个目录中。之后,我将那些具有相同日期的文件处理为 1 个文件。

简而言之:每个目录中相同日期的 3 个文件被处理为 1 个文件。

这是我的代码:

missing_dates = ['20200907', '20200908', '20200909']

root=Path(r'c:\data\FF\Desktop\new_location\middle_stage_preprocessed_district')

data_per_date = dict()
for missing_date in missing_dates:
    print(f"processing {missing_date}")
    files=[fn for fn in (e for e in root.glob(f"**/*_{missing_date}.txt") if e.is_file())]
    if len(files) != 3:
        # stop processing, check other date
        continue

    for file in files:
        with open(file, 'r') as log_file:
            reader = csv.reader(log_file, delimiter = ',')
            next(reader) # skip header
            for row in reader:
                if filter_row(row):
                    vehicle_loc_dict[(row[9], location_token(row))].append(row)

    data_per_date[missing_date] = vehicle_loc_dict  
                                                                                             
for date in missing_dates:
    file_name = "MM{}-AB.dat".format(date)
    full_path = os.path.join(my_files, 'Directory_X', file_name)
    with open(full_path, 'w+') as output:
        writer = csv.writer(output, delimiter = '\t')
        writer.writerow(headers)
        writer.writerow(data)
        vehicle_loc = data_per_date[date]
        for vehicle_loc_list in vehicle_loc.values():
            for record_group in group_records(vehicle_loc_list):
                writer.writerow(output_record(record_group))

我的文件结构是这样的:

├── dir_1
│   ├── XX_20200907.txt
│   └── XX_20200908.txt
├── dir_2
│   ├── YY_20200907.txt
│   └── YY_20200908.txt
└── dir_3
    ├── ZZ_20200907.txt
    └── ZZ_20200908.txt

我收到以下错误,但我不知道为什么。

Traceback (most recent call last):

  File "C:\data\FF\Desktop\Python\Python\Official_part1.py", line 271, in <module>
    vehicle_loc = data_per_date[date]

KeyError: '20200909'

【问题讨论】:

  • 1) 分享您的文件 official_part1.py 2) 错误在第 271 行:可能没有密钥 20200909。您可以添加if control 以给出错误但继续或使用try 结构等等。有很多不同的方法可以做到这一点。基本上,您正在使用不存在的键访问字典。你想让我做什么?继续处理文件并给出警告?你可以!
  • @Leos313 没错,没有键 20200909 因为它也不存在于我的结构中。 official_part1.py 只是我脚本的名称...
  • 我知道这是您的脚本名称。我刚刚问你是否可以分享它,以便我们阅读! :)
  • @Leos313... 我在我的问题中分享了我的脚本。第 271 行是vehicle_loc = data_per_date[date] 行。奇怪的是它抓住了日期 20200909,因为那是一个仅存在于 missing_dates 而不是我的文件结构中的日期..

标签: python list loops dictionary if-statement


【解决方案1】:

只是关键字20200909 不在您的字典中。您可以添加一种控制机制来捕获您的错误并通过警告、错误、异常。有很多方法可以解决您的问题。你的问题是:你想做什么?错误退出?继续处理?

【讨论】:

  • 我不希望出现任何错误,所以我希望我的代码继续使用现有的关键字...如何做到这一点?
  • 我想一个简单的 Try and except 块应该可以解决问题
猜你喜欢
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多