How can I use the 'newline' keyword argument for 'open' in 2.7?

Question:

I tried this code:

import urllib2
from bs4 import BeautifulSoup
import csv
#Use request for tokens
import requests
import json

def write_csv2(filename, table):
    with open(filename, 'w', newline = '') as csvfile:
        out_csv = csv.writer(csvfile)
        out_csv.writerows(table)

but I get an exception saying that ‘newline’ is an invalid keyword. Does this not work in Python 2.7? How can I specify the newline character when opening a file in text mode?

Asked By: eah

||

Answers:

In Python 2.x, the io standard library module provides the same interface for accessing files and streams that is the default in Python 3.x. Try using io.open(), which supports the newline keyword argument:

>>> import io
>>> with io.open(filename, 'w', newline='') as csvfile:
...     out_csv = csv.writer(csvfile)
...     out_csv.writerows(table)
Answered By: Ozgur Vatansever
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.