python提示line3_Python3 csv编写器失败,出现错误“ TypeError:'newline'是此函数的无效关键字参数...

1586010002-jmsa.png

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 done:

I can ingest the csv file just fine, and print the output row-by-row to the console. That code looks like this:

with open(txtpath, mode='r', newline='') as f:

fReader = csv.reader(f)

for rows in fReader:

print(rows)

This does exactly what it's supposed to, and spot checking the output confirms that the rows are being read correctly.

The Problem:

According to the official Python3 Documentation on csv.writer, "If csvfile is a file object, it should be opened with newline='' 1." My code looks like this:

with open(csvpath, 'w') as g:

gWriter = csv.writer(g, newline='')

gWriter.writerows(rows)

so all together, it looks like this:

with open(txtpath, mode='r', newline='') as f:

fReader = csv.reader(f)

for rows in fReader:

print(rows)

with open(csvpath, 'w') as g:

gWriter = csv.writer(g, newline='')

gWriter.writerows(rows)

However, when I run the code with both Pycharm (Anacondas 3.4 selected as project interpreter) and from the console with python3 mycode.py, both results tell me that newline "is an invalid keyword argument for this function" and references line 42, which is where my writer object is instantiated. I ran it through the debugger and it craps out as soon as I try to create the writer object. If I don't add the newline argument it asks for a dialect specification, so that doesn't work, either.

I'm sure there's something blindingly obvious that I'm missing, but I can't see it.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值