Python文件()函数 [英] Python file() function

查看:25
本文介绍了Python文件()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在改编一段旧代码以符合 Python 3,我遇到了这个单独的脚本

I've been adapting an old piece of code to be Python 3 compliant and I came across this individual script

"""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 第一行失败:

On the second function, retrieve_text the first line fails with:

Traceback (most recent call last):
  File ".anpr.py", line 15, in <module>
    text = image_to_string(Img)
  File "C:UsersernaDocumentsGitHubPython-ANPRpytesser.py", line 35, in image_to_string
    text = util.retrieve_text(scratch_text_name_root)
  File "C:UsersernaDocumentsGitHubPython-ANPRutil.py", line 10, in retrieve_text
    inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined

这是一个已弃用的功能还是其他问题?我应该用 file()"noreferrer">open()?

Is this a deprecated function or another problem alltogether? Should I be replacing file() with something like open()?

推荐答案

在 Python 2 中,openfile 几乎是等价的.file 是类型,open 是一个函数,名字稍微友好一些;两者都采用相同的参数并在调用时执行相同的操作,但不鼓励调用 file 来创建文件,并且尝试使用 isinstance(thing, open) 进行类型检查不会不工作.

In Python 2, open and file are mostly equivalent. file is the type and open is a function with a slightly friendlier name; both take the same arguments and do the same thing when called, but calling file to create files is discouraged and trying to do type checks with isinstance(thing, open) doesn't work.

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

In Python 3, the file implementation in the io module is the default, and the file type in the builtin namespace is gone. open still works, and is what you should use.

这篇关于Python文件()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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