Python Dict to CSV:应为缩进B

2024-06-02 05:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试将输出写入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()))

完全回溯:

^{pr2}$

Tags: andcsvtoinimportforosas
1条回答
网友
1楼 · 发布于 2024-06-02 05:59:20

如果您在这里提交的代码与您的计算机上的代码完全相同,则似乎存在空格和制表符混合在一起。如果我复制你问题中出现的代码,它会以空格缩进;但是,如果我按“编辑”然后检查代码,前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的常见原因有三种:

  • 忽略或忘记缩进
  • 缩进部分的注释块
  • 缩进中混合制表符和空格

相关问题 更多 >