Python 字典转 CSV:需要一个缩进块

Python Dict to CSV: Expected an Indented Block

尝试将输出写入 csv 并出现缩进错误。我确定这是一个愚蠢的错误,但我不明白为什么会抛出它。

#!/usr/bin/env python

import csv
import copy
import os
import sys
import glob

#get current working dir, set count, and select file delimiter
os.chdir('/Users/Briana/Documents/Misc./PythonTest')

#parses through files and saves to a dict
series = {}
for fn in glob.glob('*.txt'):
    with open(fn) as f:
        series[fn] = (1 for line in f if line.strip() and not line.startswith('#')) 

print series

#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f: 
    w = csv.DictWriter(f, series.keys()) #error thrown here
    w.writeheader()
    w.writerow(sum(names.values()))

完整追溯:

Fri Jul 24 03:13 PM [Briana PythonTest] (dev) $ ./SeriesCount.py 
File "./SeriesCount.py", line 22 
    w = csv.DictWriter(f, series.keys()) 
                                       ^ 
    IndentationError: expected an indented block

如果您在此处完全提交了您计算机上的代码,那么似乎 空格和制表符混合在一起.如果我复制出现在您的问题中的代码,它会始终以空格缩进;但是,如果我按 "edit" 然后检查代码,前 21 行用空格缩进,第 22-24 行用制表符缩进。下面的代码修复了这个错误;请注意完全按照此处显示的方式复制它:

#!/usr/bin/env python

import csv
import copy
import os
import sys
import glob

#get current working dir, set count, and select file delimiter
os.chdir('/Users/Briana/Documents/Misc./PythonTest')

#parses through files and saves to a dict
series = {}
for fn in glob.glob('*.txt'):
    with open(fn) as f:
        series[fn] = (1 for line in f if line.strip() and not line.startswith('#')) 

print series

#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f:
    w = csv.DictWriter(f, series.keys()) #error thrown here
    w.writeheader()
    w.writerow(sum(names.values()))

IndentationError: expected an indented block的三个常见原因:

  • 完全忽略或忘记缩进
  • 注释掉缩进块的一部分
  • 在缩进中混用制表符和空格