Python newb : What's preventing this function from printing?

标签 python xml csv

背景

我用 python 的工作不多,但我想用它为我生成一些重复的 XML。现在,我只想解析 CSV,然后将这些值传递到 XML 节中。

有一个问题:在编写 XML 之前,我需要重写一些 CSV。我有一些 if 语句来为我处理这个问题,我决定通过将它移到一个单独的函数中来减少困惑。

这就是我的问题出现的地方。我的 writeTypes 函数似乎按预期工作但是当我返回重写的 csvDict 实例时,我无法再打印值。

显然我遗漏了一些东西,可能很简单 - 但是什么?脚本下面有评论。

脚本

import csv

def parseCSV(vals):

    # read the csv

    dictReader = csv.DictReader(open(vals, 'rb'), fieldnames=['name', 'type', 'nullable', 'default', 'description', '#'], delimiter=',', quotechar='"')

    # some repetitive xml; I will finish this portion later...

    stanza = '''
    <var name="{0}" precision="1" scale="None" type="{1}">
        <label>{2}</label>
        <definition><![CDATA[@{3}({4})]]></definition>
    </var>'''

    # a function that simply writes new values to dictionary entries 

    writeTypes(dictReader)

    # I'm confused here - nothing is printed to the console. 
    # If i comment my 'writeTypes function, prints as expected

    for i in dictReader:
        print i
        print i['type']


# function to rewrite 'types' key in dictionary set
def writeTypes(d):

    for i in d:
        if i['type'] == 'text':
            i['type'] = 't'
        elif i['type'] == 'boolean':
            i['type'] = 'l'
        elif i['type'] == 'double precision':
            i['type'] = 'd'
        elif i['type'] == 'integer':
            i['type'] = 'i'
        else:
            i['type'] = i['type']

         # unsurprisingly, this function does seem to print the correct values    
        print i

    # it seems as though there's something wrong with this return statement...
    return d

示例 CSV

(从 .gov 网站提取的公共(public)数据)

Name,Type,Nullable,Default,Description,#
control,text,true,,,1,false
flagship,boolean,true,,,1,false
groupid,text,true,,,1,false
hbcu,text,true,,,1,false
hsi,text,true,,,1,false
iclevel,text,true,,,1,false
landgrnt,text,true,,,1,false
matched_n_00_10_11,boolean,true,,,1,false
matched_n_05_10_6,boolean,true,,,1,false
matched_n_87_10_24,boolean,true,,,1,false
name,text,true,,,1,false
name_short,text,true,,,1,false
school,text,true,,,1,false
sector,text,true,,,1,false
sector_revised,text,true,,,1,false
top_50,boolean,true,,,1,false
virginia,boolean,true,,,1,false

最佳答案

dictReader 是一个迭代器,一旦它读完 CSV 文件,它就会耗尽:进一步的迭代将不会做任何事情。

解决此问题的方法是在 writeTypes 中创建一个新的字典列表,这样您就可以在此处而不是在原始列表中分配值。然后您可以返回该列表,并在 main 函数中对其进行迭代。

关于Python newb : What's preventing this function from printing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290698/

相关文章:

java - apache-tomcat-9.0.0.M10 : Change Context-Path in META-INF/context. xml 不工作

python - reddit 的 feedparser 返回空

python - 将数据帧列转换为日期时间以进行重新映射

java - 如果下一个标签位于新行上,XmlPullParser 读取 null

Java 将新列附加到 csv 文件

Java : Automatically set array dimensions based on number of columns in CSV file

python - 查看非常大的 CSV 文件的一部分?

python - 基于生成器的 for 循环和基于列表的 for 循环会产生不同的输出?

python - 同时运行具有两个不同参数的同一脚本

c# - 进程无法访问文件,因为它被另一个进程使用