【发布时间】: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