Search code examples
pythoncsvparsingquoting

csv writer in python adding double quote when copying data from another csv file, So I just need to know how to copy exactly the same data


#Reading from csv file
with open('py_csv/oscar_age_male.csv','r') as csv_file:
    csv_reader=csv.reader(csv_file)

    #Creating new file and opening it and changing delimiter
    with open('py_csv/newfile.csv','w')as newfile:
        csv_writer=csv.writer(newfile)

#Writing Row by row
        for line in csv_reader:
            csv_writer.writerow(line)

Data from originals file=

1, 1928, 44, "Emil Janning", "The Last Command, The Way of All Flesh"
2, 1929, 41, "Warner Baxter", "In Old Arizona"

Data after being copied=

1, 1928, 44," ""Emil Janning"""," ""The Last Command"," The Way of All Flesh"""
2, 1929, 41," ""Warner Baxter"""," ""In Old Arizona"""

Solution

  • The problem is the spaces after the commas. Quotes are allowed around a field in a CSV, but since the field starts with a space, the quotes don't appear to be surrounding the whole field value. So they're being treated as literal quotes that need to be doubled in the output.

    Use the skipinitialspace option to ignore those spaces.

    csv_reader=csv.reader(csv_file, skipinitialspace=True)