我希望输出采用以下形式:
dic = {size1:file/path1, size2:file/path2}
但是我在每个组合的单独字典中得到的内容,例如:
{size1:file/path1}
{size2:file/path2, size1:file/path1, ...}
这是我想出的代码,任何人都可以纠正我的代码。
import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
sys.stdout = outfile
for cdir, dir, files in os.walk(r'/Users'):
for file in files:
if file.endswith('.py'):
filename = os.path.join(cdir, file)
size = os.path.getsize(filename)
records[size] = filename #records = {size:filename}
print records #how do I use dict.update() here?
sys.stdout = out
最佳答案
您的代码中有两个问题。第一个是你应该将 print 放在循环之外。第二个是可能有两个文件大小相同,最好将它们放在一个列表中。
import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
sys.stdout = outfile
for cdir, dir, files in os.walk(r'/Users'):
for file in files:
if file.endswith('.py'):
filename = os.path.join(cdir, file)
size = os.path.getsize(filename)
records.setdefault(size, []).append(filename)
print records
sys.stdout = out
关于python - 使用Python中的循环将项目添加到现有字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30283629/