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>You can do it very efficiently with Pandas--this will be good if your file is very large:</p>

<pre><code>import pandas as pd
import sys

with open('t.txt') as infile:
    title = next(infile)
    infile.seek(0)
    table = pd.read_csv(infile, '|', header=1, dtype=str)

table.rename(columns={'Unnamed: 9':''}, inplace=True)

table[' Zip   '] = table[' Zip   '].str.replace("'", "")
table[' OPEID  '] = table[' OPEID  '].str.replace("'", "")

sys.stdout.write(title)
table.to_csv(sys.stdout, '|', index=False)
</code></pre>

python csv