patternpythonMinor
Converting a csv to vcards in Python
Viewed 0 times
convertingcsvpythonvcards
Problem
Context: I wrote a simple as an answer to a problem in Unix.SE and it was suggested to me to post it here for review.
A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.
This was my solution:
Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.
A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.
This was my solution:
#!/usr/bin/python
import csv
import sys
def convert(file):
reader = csv.reader(open(file, 'rb'))
for row in reader:
print 'BEGIN:VCARD'
print 'VERSION:2.1'
print 'N:' + row[0] + ';' + row[1]
print 'FN:' + row[1] + ' ' + row[0]
print 'TEL;HOME;VOICE:' + row[9]
print 'END:VCARD'
def main(args):
if len(args) != 2:
print "Usage:"
print args[0] + " filename"
return
convert(args[1])
if __name__ == '__main__':
main(sys.argv)Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.
Solution
Read about the
That guarantees that the file is closed and all OS resources released.
with statement and ALWAYS use it with file operationswith open( somefilename, 'rb' ) as source:
reader = csv.reader( source )
for row in reader:
etc.That guarantees that the file is closed and all OS resources released.
Code Snippets
with open( somefilename, 'rb' ) as source:
reader = csv.reader( source )
for row in reader:
etc.Context
StackExchange Code Review Q#3517, answer score: 5
Revisions (0)
No revisions yet.