0

我对 Python 比较陌生,但遇到以下问题。我正在尝试编写一个程序来读取个人信息的 CSV 文件,然后根据输入的 ID 号显示个人信息。

它几乎可以完美地工作,除了当我按 id 号搜索时,除了我想要的结果之外,它还会返回所需结果之前的所有结果(行)。

我正在将 CSV 文件读入字典。然后,我根据 CSV 中的名称从文件中动态命名字段(理论上,CSV 文件可以包含 2 列数据或 100 列,只要有一个名为“id”的字段)。

csvfile.txt 看起来像:

id,name,age
1,jay,35
2,jen,36
3,sam,38
4,mike,26

我想要的是当我搜索 id "1" 时,它返回:

"
id: 1
name: Jay
age: 35
"

...确实如此....但是如果我搜索 id "3",我会得到:

"
id: 1
name: Jay
age: 35

id: 2
name: Jen
age: 36

id: 3
name: Sam
age: 38
"

我不明白为什么它不只是返回我要求的一行......这是代码的核心:

def runprogram():
import csv
file = open(csvfile.txt, "r") #open my test file
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')    

totalfields = (len(reader.fieldnames)) #count all the fields in the files for the purpose of for looping.

result={} #new dictionary named result

resultfields = ""

i=1
for row in reader:
    for i in range(1,totalfields):
        resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n"
        i+1
    result[row['id']] = resultfields #storing each line from the CSV into the results dictionary under the key "id"

#this was just some code so I could exit my program by typing "exit" in the input box...
idvalue=""

while idvalue != "exit":   
    #display the box in which to enter a id number

    if idvalue =="":    
        message = "Enter id Number"
    else:
        message = result[idvalue]

    #using easyGUI for my input and display boxes.    
    idvalue = eg.enterbox(msg=message,title='Print Results', default='', strip=True)

    if idvalue:
        identered = "1"#this was used for testing.           
        printresults(results[idvalue]) #call printresults function
    else:
        programmenu()

    if idvalue =="exit":
        exit()

def printresults(results):
        output = "Information Requested:\n" + results

        print(output)

任何帮助将不胜感激!

4

1 回答 1

2

您需要为您处理的每一行重新初始化结果字段。

#!/usr/bin/python
import csv
def printresults(results):
    print ("Information Requested:\n" + results)

file = open("/tmp/csvfile.txt", "r")
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')

totalfields = (len(reader.fieldnames))
result={}

for row in reader:
    resultfields = ""
    for i in range(1,totalfields):
        resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n"
    result[row['id']] = resultfields

idvalues = ["exit", "4"]
while 1:
    idvalue = idvalues.pop() #eg.enterbox(msg=message,title='Print Results', default='', strip=True)                               

    if idvalue == "":
        message = "Enter id Number"

    elif idvalue =="exit":
        print "done"
        exit()

    else:
        message = result[idvalue]
        print(message)

输出现在看起来像:

name: mike
age: 26

done
于 2013-10-28T23:16:52.980 回答