Reputation: 9512
I'm runing Python 3.6.8 and trying to read the size of a text file, but I get the error "AttributeError: '_io.TextIOWrapper' object has no attribute 'content_length'". The get_file_object_size function works when I pass it a file posted in an HTTP multipart/form-data post (using Flask), but when I try to read a text file directly from the file system, I get the error.
setup/db_setup.py:
file_path = 'myfile.txt'
# Generates the error
get_file_size_by_file_path(file_path)
setup/../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)
generates error:
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'
Upvotes: 0
Views: 975
Reputation: 1212
When you're using flask, I suspect your "file" comes in as a flask.Request
object, which does have the property content_length
.
When you pass it a (open) local file, it's of type _io.TextIOWrapper
, which as you can see from the exception, does not have a content_length
property/attribute.
If you want to check the size of a local file, you'll need to go about it differently. The .stat()
method from either the os
or pathlib
module can help with that:
>>> from pathlib import Path
>>> Path('file.txt').stat().st_size
19
>>> import os
>>> os.stat('file.txt').st_size
19
Upvotes: 4