Search code examples
pythonpython-3.xcsvopencsv

How to remove double quotes(") in csv file with Python?


My input in csv file is like below:

   “No”    “ename” age  “gender”   “salary”
    1   “aaa”   23     f          1000
    2   “bbb”   24     m          2000
    3   “ccc”   25    “f”         3000
    4   “ddd”   35     m          4000
    5   “eee”   27     f          5000

Below code is written to remove quotes given in .csv file.

import csv

csv.register_dialect('myDialect', delimiter=',', doublequote=False,
                     quoting=csv.QUOTE_NONE, skipinitialspace='True')

f = open("pythonFiles/normal.csv", 'r')

normal = csv.reader(f, dialect='myDialect')

for data in normal:
    print(data, len(data))

The output is shown below. I want to remove all of the quotes.

['“No”', '“ename”', 'age', '“gender”', '“salary”'] 
['1', '“aaa”', '23', 'f', '1000'] 
['2', '“bbb”', '24', 'm', '2000'] 
['3', '“ccc”', '25', '“f”', '3000'] 
['4', '“ddd”', '35', 'm', '4000'] 
['5', '“eee”', '27', 'f', '5000'] 

Solution

  • Maybe you could just use replace(...)?

    for data in normal:
        data = [d.replace('“', '').replace('”', '') for d in data]
        print(data, len(data))
    

    You can also do lstrip(...) and rstrip(...) if you want to keep internal quotes intact:

    for data in normal:
        data = [d.lstrip('“').rstrip('”') for d in data]
        print(data, len(data))
    

    Please note that the quotes you are using are "left double quote" () and "right double quote" () not just simple "double quote" (").