0

I am using python to parse CSV file but I face an issue how to extract "Davies" element from second row.

CSV looks like this

"_submissionusersID","_submissionresponseID","username","firstname","lastname","userid","phone","emailaddress","load_date"
"b838b35d-ca18-4c7c-874a-828298ae3345","e9cde2ff-33a7-477e-b3b9-12ceb0d214e0","DAVIESJO","John","Davies","16293","","john_davies@test2.com","2019-08-30 15:37:03"
"00ec3205-6fcb-4d6d-b806-25579b49911a","e9cde2ff-11a7-477e-b3b9-12ceb0d934e0","MORANJO","John","Moran","16972","+1 (425) 7404555","brian_moran2@test2.com","2019-08-30 15:37:03"
"cc44e6bb-af76-4165-8839-433ed8cf6036","e9cde2ff-33a7-477e-b3b9-12ceb0d934e0","TESTNAN","Nancy","Test","75791","+1 (412) 7402344","nancy_test@test2.com","2019-08-30 15:37:03"
"a8ecd4db-6c8d-453c-a2a7-032553e2f0e6","e9cde2ff-33a7-477e-b3b9-12ceb0d234e0","SMITHJO","John","Smith","197448","+1 (415) 5940445","john_smith@test2.com","2019-08-30 15:37:03"

I'm stuck here:

with open('Docs/CSV/submis/submis.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
JohnPix
  • 1,595
  • 21
  • 44

3 Answers3

1

You are absolutely correct with the code and each and every row is returned as a Dict so you need to parse the Dict and obtain the required results you want to, as shown below.

import csv
with open('/home/liferay172/Documents/Sundeep/stackoverflow/text.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        print(row)
        print("Username :: "+row['username'])
        print("Firstname :: "+row['firstname'])
        print("Lastname :: "+row['lastname'])

enter image description here

For a specific row

import csv
rowNumber = 1
with open('/home/liferay172/Documents/Sundeep/stackoverflow/text.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    print(list(csv_reader)[rowNumber-1]['lastname']) # -1 as the index starts from 0

Returns > Davies

Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
1

You can convert the CSV reader object to a list and then it can be accessed by index.

import csv
with open('Docs/CSV/submis/submis.csv') as csv_file:
    csv_reader = list(csv.reader(csv_file))
    # 2nd row
    print(csv_reader[1])
    # 2nd row 3rd column
    print(csv_reader[1][2])
Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
Nitin_k29
  • 341
  • 1
  • 3
  • 7
1

Here's how to put, for example, "Davies" record in result variable and also print its data if found.

import csv
with open('/home/liferay172/Documents/Sundeep/stackoverflow/text.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        if (row['username'] == "Davies"):
            match = row
            print("Username:\t" + row['username'])
            print("Firstname:\t" + row['firstname'])
            print("Lastname:\t" + row['lastname'])
            break
print(match)
Pitto
  • 8,229
  • 3
  • 42
  • 51