尝试将输出写入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
答案 0 :(得分:0)
如果您在此处完全提交了代码,那么 空格和标签就会混合在一起。如果我复制你问题中出现的代码,它会一致地缩进,带有空格;但是,如果我按“编辑”然后检查代码,前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
有三个常见原因: