How to write output file in CSV format in python?

前端 未结 4 1865
忘了有多久
忘了有多久 2021-01-07 04:11

I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.

Getting error in Python 3.5:

4条回答
  •  臣服心动
    2021-01-07 04:36

    Others have answered that you should open the output file in text mode when using Python 3, i.e.

    with open('out.csv', 'w', newline='') as resultFile:
        ...
    

    But you also need to parse the incoming CSV data. As it is your code reads each line of the input CSV file as a single string. Then, without splitting that line into its constituent fields, it passes the string to the CSV writer. As a result, the csv.writer will treat the string as a sequence and output each character , including any terminating new line character, as a separate field. For example, if your input CSV file contains:

    1,2,3,4
    

    Your output file would be written like this:

    1,",",2,",",3,",",4,"
    "
    

    You should change the for loop to this:

    for row in csv.reader(f1):
        # process the row
        wr.writerow(row)
    

    Now the input CSV file will be parsed into fields and row will contain a list of strings - one for each field. For the previous example, row would be:

    for row in csv.reader(f1):
        print(row)
    
    ['1', '2', '3', '4']
    

    And when that list is passed to the csv.writer the output to the file will be:

    1,2,3,4
    

    Putting all of that together you get this code:

    import csv
    
    with open('input_1.csv') as f1, open('out.csv', 'w', newline='') as resultFile:
        wr = csv.writer(resultFile, dialect='excel')
        for row in csv.reader(f1):
            wr.writerow(row)
    

提交回复
热议问题