私はPythonに比較的慣れていないため、次のことに問題があります。個人情報のCSVファイルを読み込み、ID番号を入力することで個人情報を表示するプログラムを書こうとしています。
ID番号で検索すると、必要な結果に加えて、目的の結果に先行するすべての結果(行)が返されることを除いて、ほぼ完全に機能しています。
CSV ファイルを辞書に読み込んでいます。次に、CSV の名前に基づいてファイルからフィールドに動的に名前を付けています (理論的には、「id」という名前のフィールドが 1 つある限り、CSV ファイルには 2 列または 100 列のデータを含めることができます)。
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
"
求めている1行だけを返さない理由がわかりません...コードの核心は次のとおりです。
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)
どんな助けでも大歓迎です!