user1195192 user1195192 - 2 months ago 11
Python Question

Best way to read and write two files?

Folks, looking to get the suggestions on the best way to deal with the following task:

1. Read data off of a CSV file.

2. Edit an XML file based on the data read in Step 1.

I am a Python noob. So far I am able to read the data off of a CSV file. In my Java world, I would simply pass the "read" data off to a method and iterate over and edit the XML file in that method.

Can I do something similar in Python? Is there a more efficient and cleaner way of achieving the same in Python?

import csv

ifile = open('my-file.csv', "rb")
reader = csv.reader(ifile)

rownum = 0
for row in reader:
#print row
if rownum == 0:
header = row
else:
colnum = 0
name = row[1]
desig = row[5]
print("Name: ", name)
print("Designation: ", desig)


rownum += 1
if rownum == 10:
break

ifile.close()

Answer

Very similar to your solution, just uses enumerate and with instead of open and close:

import csv

with open('my-file.csv', 'rb') as ifile:
    reader = csv.reader(ifile)
    for rownum, row in enumerate(reader):
        #print row
        if rownum == 0:
            header = row
        else:
            colnum = 0
            name = row[1]
            desig = row[5]
            print("Name: ", name)
            print("Designation: ", desig)
        if rownum == 10:
            break