Tag Archives: DataScience

Python TypeError: ‘newline’ is an invalid keyword argument for this function

Write a code saved as a CSV file

 with open(outputFile, 'w', newline='') as csvfile:
     writer = csv.writer(csvfile)
     for item in sortsim:
         writer.writerow([item[0], item[1], item[2]])

Something’s wrong

Traceback (most recent call last):
  File "/data/ml/shan-als.py", line 54, in <module>
    with open(outputFile, 'w', newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function

Guess is the reason for the version, plus the version of judgment.
Py2 can use ‘WB’, PY3 can use newline = ‘.

    import sys
    if sys.version >= '3':
        with open(outputFile, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])
    else:
        with open(outputFile, 'wb') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])