Python 2和3 csv阅读器 [英] Python 2 and 3 csv reader

查看:221
本文介绍了Python 2和3 csv阅读器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用csv模块来读取utf-8 csv文件,并且由于编码,我有一些麻烦为python 2和3创建一个通用代码。

I'm trying to use the csv module to read a utf-8 csv file, and I have some trouble to create a generic code for python 2 and 3 due to encoding.

这里是Python 2.7中的原始代码:

Here is the original code in Python 2.7:

with open(filename, 'rb') as csvfile:
    csv_reader = csv.reader(csvfile, quotechar='\"')
    langs = next(csv_reader)[1:]
    for row in csv_reader:
        pass

但是当我使用python 3运行它,它不喜欢的事实,我打开文件没有我试过这个:

But when I run it with python 3, it doesn't like the fact that I open the file without "encoding". I tried this:

with codecs.open(filename, 'r', encoding='utf-8') as csvfile:
    csv_reader = csv.reader(csvfile, quotechar='\"')
    langs = next(csv_reader)[1:]
    for row in csv_reader:
        pass


$ b $ p现在python 2无法解码for循环中的行。

Now python 2 can't decode the line in the "for" loop. So... how should I do it ?

推荐答案

实际上,在Python 2中,文件应该以二进制模式打开,在Python 3中的文本模式。 也在Python 3中 newline =''应该指定(您忘记了)。

Indeed, in Python 2 the file should be opened in binary mode, but in Python 3 in text mode. Also in Python 3 newline='' should be specified (which you forgot).

您必须在if块中打开文件。 p>

You'll have to do the file opening in an if-block.

import sys

if sys.version_info[0] < 3: 
    infile = open(filename, 'rb')
else:
    infile = open(filename, 'r', newline='', encoding='utf8')


with infile as csvfile:
    ...

这篇关于Python 2和3 csv阅读器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆