earnThis
earnThis

Reputation: 61

Read, change, then write csv data in python

How can I output the data I've formatted to a csv file? I believe it's possible to write each line as I clean them but I'm not sure how. The basic goal I'm trying to achieve is to iterate through all rows of the csv and change only the items in the rows that meet the criteria of the for loop. Then output all the changed and unchanged rows back out to another csv.

import csv
import sys
import re

fileToClean = open(sys.argv[1], 'rb')
readerObj = csv.reader(fileToClean)

for row in readerObj:
  for item in row:
    if " TB" in item:
      newitem = item.replace(" TB","")
      result = re.sub('[^0-9]','',newitem)
      result = float(newitem) * 1024
      result = round(result, 2)
    elif " MB" in item:
      newitem =  item.replace(" MB", "")
      result = re.sub('[^0-9]','',newitem)
      result = float(result) / 1000
      result = round(result, 2)
    elif " GB" in item:
      newitem = item.replace(" GB", "")
      result = re.sub('[^0-9]','',newitem)
      result = float(result)
      result = round(result, 2)

Upvotes: 1

Views: 3801

Answers (2)

Daniel
Daniel

Reputation: 2459

One simple way to accomplish what you are trying to do is to read your file as a list, make your changes, and then write the list to a new file:

import csv
import sys
import re

fileToClean = open(sys.argv[1], 'rb')
readerObj = list(csv.reader(fileToClean))

# ...iterate through readerObj, changing whatever items you want...

with open("newFile", "w") as csvfile:
    wr = csv.writer(csvfile,delimiter=',')
    for line in readerObj:
        wr.writerow(line)

Upvotes: 2

Xiongbing Jin
Xiongbing Jin

Reputation: 12087

newfile = open("test.csv", "w")
for row in readerObj:
  newrow = []
  for item in row:
    if " TB" in item:
      item = item.replace(" TB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item) * 1024
      item = round(item, 2)
    elif " MB" in item:
      item =  item.replace(" MB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item) / 1000
      item = round(item, 2)
    elif " GB" in item:
      item = item.replace(" GB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item)
      item = round(item, 2)
    newrow.append(str(item))
  newfile.write(','.join(newrow) + '\n')
newfile.close()
fileToClean.close()

Upvotes: 1

Related Questions