python - 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'
解决方案
当您使用烧瓶时,我怀疑您的“文件”作为一个flask.Request
对象出现,它确实具有属性content_length
.
当您将一个(打开的)本地文件传递给它时,它的类型_io.TextIOWrapper
为 ,正如您从异常中看到的那样,它没有content_length
属性/属性。
如果要检查本地文件的大小,则需要以不同的方式进行。or模块中的.stat()
方法可以帮助解决这个问题:os
pathlib
>>> from pathlib import Path
>>> Path('file.txt').stat().st_size
19
>>> import os
>>> os.stat('file.txt').st_size
19
推荐阅读
- c# - 减法后如何防止int变为负数
- cmake - CMake - 无法为 VS2015 设置源文件属性
- css - 图像显得太暗
- arrays - 设置键值对后 Swift 字典返回 nil
- reactjs - IE11、Adobe Analytics、带有错误消息的 React-Router:“不变违规:您不应该使用
外面 " - mysql - 如何根据条件获取别名字段的 SUM?
- android - 让每个观察者在订阅/观察时只接收 *new* LiveData
- c++ - 打开文件的正确模式是什么,以便 seekp() 的工作方式与在默认模式下打开的文件中的工作方式相同?
- angular - Angular 4 无法绑定到“xxx”,因为它不是 xxx 错误的已知属性
- reactjs - 我目前有一个对象数组,每个对象都有投资组合中每个项目的道具:将显示的名称、ID 和图像