python2.7 下操作csv的几个问题

因为需要操纵csv文件,在网上抄了一段代码,结果一连串出错。
我是python2.7环境

csvfile = open('aaa.csv','w',encoding='utf-8', newline='')

上来就报错

TypeError: file() takes at most 3 arguments (4 given)

不支持4个参数

Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

>>>

估计抄来的代码是python3的吧
改一下,再执行

csvfile = open('aaa.csv','w', newline='')

又报错

TypeError: 'newline' is an invalid keyword argument for this function

好吧,newline也是不支持的。
改了一下,只有2个参数了,再执行

csvfile = open('aaa.csv','w')

居然又报错了

IOError: [Errno 22] invalid mode ('w') or filename:

那尼,难道这2个参数也不行???
查了网上,原来这个方法中,filename这个参数必须是Unicode编码的参数,可以按照以下方式修改

csvfile = open('aaa.csv'.decode('utf-8'),'w')

总算不报错了。
最后再查一下newline干嘛用的,原来是实现避免行距2倍。可以用以下方式替代

csvfile = open('aaa.csv'.decode('utf-8'),'wb')

wb表示以“二进制 写”模式打开,同样可以实现避免行距2倍效果。

发布了122 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42555985/article/details/102985841