Python file()函数

发布于 2021-01-29 16:51:29

我一直在修改旧代码以使其符合Python 3,并且遇到了这个单独的脚本

"""Utility functions for processing images for delivery to Tesseract"""

import os


def image_to_scratch(im, scratch_image_name):
    """Saves image in memory to scratch file.  .bmp format will be read 
        correctly by Tesseract"""
    im.save(scratch_image_name, dpi=(200, 200))


def retrieve_text(scratch_text_name_root):
    inf = file(scratch_text_name_root + '.txt')
    text = inf.read()
    inf.close()
    return text


def perform_cleanup(scratch_image_name, scratch_text_name_root):
    """Clean up temporary files from disk"""
    for name in (scratch_image_name, scratch_text_name_root + '.txt',
                 "tesseract.log"):
        try:
            os.remove(name)
        except OSError:
            pass

在第二个函数上,retrieve_text第一行失败并显示:

Traceback (most recent call last):
  File ".\anpr.py", line 15, in <module>
    text = image_to_string(Img)
  File "C:\Users\berna\Documents\GitHub\Python-ANPR\pytesser.py", line 35, in image_to_string
    text = util.retrieve_text(scratch_text_name_root)
  File "C:\Users\berna\Documents\GitHub\Python-ANPR\util.py", line 10, in retrieve_text
    inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined

这是不赞成使用的功能还是另一个问题?我应该用file()类似的东西代替open()吗?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在Python
    2,open并且file大多是等价的。file是类型,并且open是名称稍友好的函数;两者都使用相同的参数并在调用时执行相同的操作,但是file不鼓励调用创建文件,并且尝试使用类型检查isinstance(thing, open)不起作用。

    在Python 3中,io模块中的文件实现是默认的,file内置命名空间中的类型已消失。open仍然有效,这是您应该使用的。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看