You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环遍历目录时如何向字典持续添加键值对?

Fixing Your Dictionary Population Issue

Hey there! I see the problem with your current code—you're creating a brand new empty dictionary x inside the loop every time you find a matching file. That means each new file overwrites the previous entry, so you'll only end up with the last matching file instead of all 7 you expect.

Here's how to fix this, plus some improvements to make your code more robust:

Step-by-Step Fixes

  • Initialize the dictionary outside the loop: This way, the same dictionary persists through every iteration, and you keep adding entries instead of replacing them.
  • Use os.path.join() for path concatenation: Manual slashes (\) can cause issues (especially cross-platform), so this is a safer approach.
  • Double-check time type: Your code uses st_atime (access time—when the file was last opened). If you meant modification time (when the file was last edited), use st_mtime instead.

Corrected Code

import os

path = r"C:\Users\Gronk\Downloads"
# Initialize the dictionary once, before the loop
consensus_files = {}

for file in os.listdir(path):
    if 'ConsensusData' in file:
        # Safely build the full file path
        full_path = os.path.join(path, file)
        file_stats = os.stat(full_path)
        # Use st_mtime for modification time (swap back to st_atime if you need access time)
        modification_time = file_stats.st_mtime
        # Add the file and its time to the dictionary
        consensus_files[file] = modification_time

# Verify you have all 7 entries
print(consensus_files)

Bonus: Human-Readable Times

If you want the time to be in a readable format instead of a timestamp, use the datetime module:

import os
from datetime import datetime

path = r"C:\Users\Gronk\Downloads"
consensus_files = {}

for file in os.listdir(path):
    if 'ConsensusData' in file:
        full_path = os.path.join(path, file)
        file_stats = os.stat(full_path)
        # Convert timestamp to a readable string
        readable_time = datetime.fromtimestamp(file_stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
        consensus_files[file] = readable_time

print(consensus_files)

内容的提问来源于stack exchange,提问作者user3159004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:04