我试过这段代码:
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)
但是我得到一个异常,说“换行符”是一个无效的关键字。这在 Python 2.7 中不起作用吗?如何在文本模式下打开文件时指定换行符?
请您参考如下方法:
在 Python 2.x 中,io标准库模块提供与 Python 3.x 中默认的文件和流相同的接口(interface)。尝试使用 io.open() ,它支持 newline 关键字参数:
>>> import io
>>> with io.open(filename, 'w', newline='') as csvfile:
... out_csv = csv.writer(csvfile)
... out_csv.writerows(table)
