Change values of a column in CSV file using python
<p>I am new to python and just need a small help.</p>

<p>We have a Pipe delimited CSV file which looks like this </p>

<pre><code>DATE|20160101
ID | Name | Address | City | State | Zip   | Phone | OPEID  | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 |
</code></pre>

<p>Every value of Zip and OPEID columns has apostrophes in the beginning </p>

<p>So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.</p>

<p>The new file should then look like this:</p>

<pre><code>DATE|20160101
ID | Name | Address | City | State | Zip  | Phone | OPEID | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 |
</code></pre>

<p>This code works for copying data without removing apostrophes</p>

<pre><code>import os
import csv

file1 = "D:\CSV\File1.csv"
with open(file1, 'rb') as csvfile:

         reader = csv.reader(csvfile, delimiter = '|')

         path = "D:/CSV/New"
         if not os.path.exists(path):
             os.makedirs(path)

         writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|')

         for row in reader:
             writer.writerow(row)

csvfile.close()
</code></pre>

<p>The code below would be the same for all file formats. The fact that it is a *.csv doesn't change a thing. What it actually does, is that it goes in the file from which you want to remove the apostrophes, <code>my_csv_in</code>, and parses it line by line each time replacing them with nothing (a.k.a removing). The modified lines are written in a second file, <code>my_csv_out</code>.</p>

<pre><code>my_csv_in = r'full_file_path_to_csv_in.csv'
my_csv_out = r'full_file_path_to_csv_out.csv'

with open(my_csv_in, 'r') as f_in:
    with open(my_csv_out, 'w') as f_out:
        for line in f_in:
            f_out.write(line.replace("'", ''))
</code></pre>

<p>There are probably better ways to do this that take advantage of the file being a *.csv and using the <code>csv</code> library. You can take a look at the <a href="https://docs.python.org/3/library/csv.html#csv.Dialect.quoting" rel="nofollow"><code>quoting options</code></a> in the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">documentation</a>.</p>

python csv