csv.DictReader giving unexpected results

user9081219

My CSV file:

website, username, password
google.com, test1, lamepass
instagram.com, test2, passlame

My python script:

with open(database_path) as database:
    csv_read = csv.DictReader(database)
    for card in csv_read:
        print(card['website'])

Which returns:

google.com
instagram.com

But this code:

with open(database_path) as database:
    csv_read = csv.DictReader(database)
    for card in csv_read:
        print(card['password'])

Returns:

KeyError: 'password'

I don't understand the issue, and online resources just show examples, none of them explain this problem. They do talk about KeyErrors, but they don't seem to address how the CSV file contains the key ('password'), but still returns key error.

Am I doing something wrong?

Suraj Kothari

In your csv file, there are spaces between the comma separated values. Remove them and it should work.

Othewise try this:

import csv

with open(database_path) as database:
    csv_read = csv.DictReader(database)

    for card in csv_read:
        print(card[" password"]) # notice the space!!!

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

csv.DictReaderの行数

分類Dev

orWhere giving unexpected result

分類Dev

ContainsRune giving strange results

分類Dev

JPQL not giving results

分類Dev

Java method giving unexpected return

分類Dev

sort command giving unexpected output

分類Dev

Same queries giving different results

分類Dev

IQueryable Include not giving correct results

分類Dev

行をスキップ、csv.DictReader

分類Dev

Iterating using a goroutine is giving unexpected result

分類Dev

Laravel Eloquent Repository - Query giving unexpected result?

分類Dev

Adding dates in javascript with unexpected results

分類Dev

For loop producing unexpected results in C

分類Dev

~1 and ~0 giving strange results in python 3

分類Dev

csv.DictReaderをCSVファイルに変換します

分類Dev

Python csv.DictReader:文字列を解析しますか?

分類Dev

csv.DictReaderの操作におけるdatetime.strptimeの問題

分類Dev

csv.DictReaderの行を複数回ループする

分類Dev

DictReaderを使用してCSVからリストに読み込む

分類Dev

予期しない結果をもたらすcsv.DictReader

分類Dev

csv.DictReaderの空白の列をスキップします

分類Dev

Bitwise operation results in unexpected variable size

分類Dev

Testing of spring batch job causes unexpected results

分類Dev

Perl utf8 binmode unexpected results

分類Dev

Python numpy unexpected results in arange and linspace

分類Dev

Binary reading with python gives unexpected results

分類Dev

Alter materialized view in BigQuery results in "Unexpected statement"

分類Dev

Query with several consecutive LEFT JOIN - unexpected results

分類Dev

deepcopying function variable gives unexpected results

Related 関連記事

ホットタグ

アーカイブ