python - read in one row of csv file (based on input if i can) with DictReader, then format and write to new file -


i'm trying read in csv file many rows , columns; print 1 row, in particular format, text file, , hashing on values. far, have been able read in file, parse thru using dictreader, find row want using if statement , print keys , values. cannot figure out how format format want in end ( key = value \n), , cannot figure how write file (much less in format want) using value of 'row' obtained below. i've been trying days , make little progress cannot work. here got work (with detail left out of results):


>>>import csv  open("c:\path_to_script\filename_brief.csv") infh:     reader = csv.dictreader(infh)     row in reader:         if row['alias'] == 'y4k':             print(row) 

result-output

{'full_name': 'jack flash', 'phone_no': '555 555-1212', 'alias': 'y4k'}


i'd ask user input alias , use determine row print. i've done ton of research new-ish python asking help! i've used pyexcel, xlrd/xlwt, thought i'd try pandas learn. got format way wanted in 1 test not row selection work--in other words, prints records rather row want. have 30 firefox tabs open trying find answer! in advance!

the following may @ least close want (i think):

import csv  open(r'c:\path_to_script\filename_brief.csv') infh, \      open('new_file.txt', 'wt') outfh:     reader = csv.dictreader(infh)     row in reader:         if row['alias'] == 'y4k':              outfh.write('full_name = {full_name}\n'                          'phone_no = {phone_no}\n'                          'alias = {alias}\n'.format(**row)) 

this write 3 lines formatted output file every matchingrow:

full_name = jack flash  phone_no = 555 555-1212 alias = y4k             

btw, **rownotation means "take entries in specified dictionary , turn them keyword arguments function call". {keyword} syntax in format string refers keyword arguments passed str.format() method.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -