0

I have a seemingly simple task with a .CSV file. I need to replace all white space with 0's for two specific columns (37, 38). I've tried the following code:

import csv

with open("C:/Temp/whiteSpace.csv", "rb") as infile, open("C:/Temp/repaired_test.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        row[37] = row[37].replace(' ', '0')
        writer.writerow(row)
        print row[37]

However, this simply writes the "whiteSpace.csv" over to "repaired_test.csv" with out editing anything.

I've found plenty on stripping whitespace (strip white spaces from file csv) but I'm not able to connect the dots and make my code work.

Sorry for the redundant question, and thank you in advance.

Community
  • 1
  • 1
Jenny
  • 65
  • 1
  • 2
  • 7

1 Answers1

0

Are you sure the character you want to replace is the blank character ()? It could be a tab or something else. You can try a regex to catch all blank chars:

>>> import re
>>> r = re.compile(r'\s')
>>> r.sub('0', 'TEXT\tSPACE TEXT')
'TEXT0SPACE0TEXT'
hcalves
  • 2,268
  • 1
  • 21
  • 17
  • Well, more specifically, I need to replace blank values (different from white space?). Eventually I need to do a join, but the blank values in the column cause the script to get hung up. – Jenny Apr 05 '13 at 06:56