【问题标题】:NameError: name 'file' is not definedNameError:名称“文件”未定义
【发布时间】:2016-08-21 19:02:59
【问题描述】:

这适用于 Python 2.7,但不适用于 3.5。

def file_read(self, input_text):

    doc = (file.read(file(input_text))).decode('utf-8', 'replace')

我正在尝试打开这个文件,input_text 是来自 argparse 的路径值。

我收到此错误。

NameError: name 'file' is not defined

我推测 Python 3.5 使用“open”而不是“file”,但我不太明白如何在这种情况下使用 open。

【问题讨论】:

  • str object has no attribute "read" 和这个有什么关系?!
  • 我希望人们在提供负面声誉方面能慢一点。只是从这里开始,而不是想把事情搞砸。
  • @FredZimmerman 是的,我同意你的观点

标签: python file python-3.x


【解决方案1】:

您的原始代码在 Python 2.7 中工作,但那里的风格很糟糕。用于此用途的 file 很久以前就被弃用了,而是使用 open,而不是调用 file.read 将文件作为参数传递,您应该只在返回的对象上调用 .read 方法。

在 Python 2 上编写代码的正确方法是

with open(input_text) as docfile:
     doc = docfile.read().decode('utf-8', 'replace')

这在 Python 3 中不起作用,因为没有模式的 open 现在默认读取 unicode 文本。此外,它会假设文件是​​本机编码并使用 strict 错误处理对其进行解码。然而,Python 3 实际上比 Python 2 更容易处理文本文件,因为您可以将编码和错误行为作为参数传递给 open 本身:

with open(input_text, encoding='utf-8', errors='replace') as docfile:
     doc = docfile.read()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多