NSH
NSH

Reputation: 11

How to create a tuple <input,output> where input is text in the column and output as row number?

I have a csv file with Name Mobile Email headers. I want to generate a tuple which has input as a name,email or mobile and output as the corresponding row number. (input,output) tuple.

Upvotes: -1

Views: 135

Answers (2)

Rajat Jain
Rajat Jain

Reputation: 1415

Refer to this docs

The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

You can use this CSV module to do the functionality.

import csv
with open('my_file.csv', 'rb') as f:
    file_reader = csv.reader(csvfile)
    for row in file_reader:
        my_tuple= tuple(row)
        print(my_tuple)

For writing in the file you can use .writerow() function

fieldnames = ['Name', 'Mobile','Email']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': x, 'Mobile': y,'Email':z})

x,y,z are variables

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 397

Is this what you mean by tuples?

import csv 
with open('file.csv', 'r', newline='') as f:
    reader = csv.DictReader(f)
    for tup in enumerate(reader):
        print(tup)

Output:

(0, OrderedDict([('name', 'abc'), ('email', '[email protected]'), ('phone', '12345678')]))
(1, OrderedDict([('name', 'lmn'), ('email', '[email protected]'), ('phone', '23456789')]))

Upvotes: 0

Related Questions