0

I am fairly inexperienced with the csv module in Python and was wondering if anyone could give any pointers. I have been looking through many other questions regarding this question but have come up with no answers for mine.

All I want to do is alter values, in which case it would be "n/a" and replace it with 0 in my csv file. These n/a values are within all columns so I can't pinpoint it to one specific column.

This is my code so far:

with open("MyCSV.csv","rb") as infile,open("Write.csv","wb") as outfile:
    reader= csv.reader(infile)
    writer= csv.writer(outfile)
    conversion= set('(n/a)')
    for row in reader:
        newrow=[''.join('0' if c in conversion else c for c in entry)for       entry in row]
        writer.writerow(newrow)

The issue I have come across in my result is that any a or n is transformed to a 0. This is obviously because it is being read that every 'n' or 'a' should be converted.

Thanks for any help someone can give.

2 Answers 2

1

set takes a sequence and uses all the items in that sequence to make the set. Since strings are sequences, what you end up with is:

set('(n/a)')
Out[7]: {'(', ')', '/', 'a', 'n'}

i.e. each individual character as an item. If you want the set to have one item, the full (n/a) string, then make a list with one item:

set(['(n/a)'])
Out[8]: {'(n/a)'}
Sign up to request clarification or add additional context in comments.

2 Comments

This is true, but the OP will still need to change the newrow line. Right now the OP is looping over characters when that's probably not intended.
This helps me understand it better, but it still does not work for me.
1

Here's a way to do using csv module

with open("MyCSV.csv","rb") as infile,open("Write.csv","wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        row = [x.replace('n/a', '0') if x == 'n/a' else x for x in row]
        writer.writerow(row)

Regex might be a better option here, something like this:

import re
with open("MyCSV.csv", "rb") as f1:
    lines = f1.read()
    for line in re.sub('n/a', '0', lines):
        print line,

1 Comment

I've never used Regex before but using this script didn't seem to work. Would you not have to write it to a csv at some point, considering we would only be reading from my original file in this script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.