简体   繁体   中英

How to output certain element from a row from CSV file, Python

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:

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'])

在此处输入图片说明

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

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])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM