首页 > 解决方案 > AttributeError:“_io.TextIOWrapper”对象没有属性“content_length”

问题描述

我正在运行 Python 3.6.8 并尝试读取文本文件的大小,但出现错误“AttributeError: '_io.TextIOWrapper' object has no attribute 'content_length'”。get_file_object_size 函数在我传递一个发布在 HTTP 多部分/表单数据帖子中的文件(使用 Flask)时起作用,但是当我尝试直接从文件系统读取文本文件时,我得到了错误。

设置/db_setup.py:

file_path = 'myfile.txt'
# Generates the error
get_file_size_by_file_path(file_path)

设置/../utils/files.py:

def get_file_object_size(fobj):
    if fobj.content_length:
        return fobj.content_length

    try:
        pos = fobj.tell()
        fobj.seek(0, 2)  #seek to end
        size = fobj.tell()
        fobj.seek(pos)  # back to original position
        return size
    except (AttributeError, IOError):
        pass

    # in-memory file object that doesn't support seeking or tell
    return 0  #assume small enough


def get_file_size_by_file_path(file_path):
    with open(file_path) as file:
        return get_file_object_size(file)

产生错误:

Traceback (most recent call last):
  File "setup/db_setup.py", line 76, in main
    ins, file_uri='myfile.txt', type=1, file_size=get_file_size_by_file_path(file_path))
  File "setup/../utils/files.py", line 20, in get_file_size_by_file_path
    return get_file_object_size(file)
  File "setup/../utils/files.py", line 2, in get_file_object_size
    if fobj.content_length:
AttributeError: '_io.TextIOWrapper' object has no attribute 'content_length'

标签: pythonpython-3.x

解决方案


当您使用烧瓶时,我怀疑您的“文件”作为一个flask.Request对象出现,它确实具有属性content_length.

当您将一个(打开的)本地文件传递给它时,它的类型_io.TextIOWrapper为 ,正如您从异常中看到的那样,它没有content_length属性/属性。

如果要检查本地文件的大小,则需要以不同的方式进行。or模块中的.stat()方法可以帮助解决这个问题:ospathlib

>>> from pathlib import Path
>>> Path('file.txt').stat().st_size
19
>>> import os
>>> os.stat('file.txt').st_size
19

推荐阅读