I have a CSV with a bunch of data, and I need to change the data in a specific row and column. I'm able to read through the file, find the row,col that I need to change, change the data, but I can't figure out how to commit that change to memory and re-write the CSV correctly.
The following code does not fail, however it is not correct. Instead of committing the changes that I make to the column (col), it just duplicates the row that I want to change. The data is unchanged, and now I just have duplicate rows where I wanted changes.
import csv
import re
from tempfile import NamedTemporaryFile
import shutil
csvName = raw_input("Enter the filename: ")
tempfile = NamedTemporaryFile(delete=False)
newSize = 0
newArea = 0
with open(csvName, 'rb') as readCSV, tempfile:
reader = csv.reader(readCSV)
writer = csv.writer(tempfile)
for row in reader:
for col in row:
if col.startswith('Connection:'):
print col
if col.startswith('Size:'):
print "Current", col
newSize = raw_input("Enter new size: ")
newArea = int(newSize)*int(newSize)
col = re.sub('[0-9]+', newSize, col)
writer.writerow(row)
if col.startswith('Area:'):
col = re.sub('[0-9]+', str(newArea), col)
writer.writerow(row)
writer.writerow(row)
shutil.move(tempfile.name, csvName)
This is an example of one bit of data that needs to be changed:
Connection: D14Conn Type: B2B Size: 140 Geometry: Square Area: 19600
My code above will simply duplicate new rows into this data, and the changes I make to col are not committed - as below
Connection: D14Conn Type: B2B Size: 140 Size: 140 Geometry: Square Area: 19600 Area: 19600