Python3 csv writer failing, exiting on error "TypeError: 'newline' is an invalid keyword argument for this function

前端 未结 4 411
盖世英雄少女心
盖世英雄少女心 2021-01-20 19:33

What I\'m trying to do:

I\'m trying to change the formatting on a csv file from space delimited to comma delimited.

What I\'ve don

相关标签:
4条回答
  • 2021-01-20 19:44

    The wording is just a bit vague. The file should be opened with newline='', but newline is not a valid option for csv.writer() itself.

    0 讨论(0)
  • 2021-01-20 19:49

    To avoid this error , open the file in 'wb' mode instead of 'w' mode. This will eliminate the need for newline. Corrected code is as follows:

    with open(csvpath, 'wb') as g:
        gWriter = csv.writer(g)
        gWriter.writerows(rows)
    
    0 讨论(0)
  • 2021-01-20 19:59

    The following will do

    with open('filename_inCSV.csv',mode='r') as csvfile:
    

    or

    with open('filename_inCSV.csv','r') as csvfile:
    
    0 讨论(0)
  • 2021-01-20 20:04

    newline does not work in with open('output.csv', 'a',newline='') as fp. It will return back an error:

    'newline' is an invalid keyword argument for this function

    I used 'ab' method and it worked without blank lines between the lines:

    with open('output.csv', 'ab',) as fp
    
    0 讨论(0)
提交回复
热议问题