python打开文件错误 [英] python open file error

查看:38
本文介绍了python打开文件错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一些文件,我知道文件中存在一些 UTF-8 编码错误,所以我将在 python3 中做的是

I am trying to open some file and I know there are some errors in the file with UTF-8 encoding, so what I will do in python3 is

open(fileName, 'r', errors = 'ignore') 

但是现在我需要使用python2,相应的方法是什么?

but now I need to use python2, what are the corresponding way to do this?

下面是我改成编解码器后的代码

Below is my code after changing to codecs

    with codecs.open('data/journalName1.csv', 'rU', errors="ignore") as file:
        reader = csv.reader(file)
        for line in reader:
            print(line) 

文件在这里https://www.dropbox.com/s/9qj9v5mtd4ah8nm/journalName.csv?dl=0

推荐答案

Python 2 不支持使用内置的 open功能.相反,您必须使用编解码器.

Python 2 does not support this using the built-in open function. Instead, you have to uses codecs.

import codecs
f = codecs.open(fileName, 'r', errors = 'ignore')

如果您决定将来需要切换 Python 版本,这适用于 Python 2 和 3.

This works in Python 2 and 3 if you decide you need to switch your python version in the future.

这篇关于python打开文件错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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