file_content is a string variable, which contains contents of the file -- it has no relation to the file. The file descriptor you open with open(from_file) will be closed automatically: file sessions are closed after the file-objects exit the scope (in this case, immediately after .read()).

Answer from Aapo Kyrola on Stack Overflow
Top answer
1 of 3
15

file_content is a string variable, which contains contents of the file -- it has no relation to the file. The file descriptor you open with open(from_file) will be closed automatically: file sessions are closed after the file-objects exit the scope (in this case, immediately after .read()).

2 of 3
3

open(...) returns a reference to a file object, calling read on that reads the file returning a string object, calling write writes to it returning None, neither of which have a close attribute.

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.

>>> a = open('a', 'w')
>>> help(a.read)
read(...)
    read([size]) -> read at most size bytes, returned as a string.

    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
>>> help(a.write)
Help on built-in function write:

write(...)
    write(str) -> None.  Write string str to file.

    Note that due to buffering, flush() or close() may be needed before
    the file on disk reflects the data written.

Theres a couple ways of remedying this:

>>> file = open(from_file)
>>> content = file.read()
>>> file.close()

or with python >= 2.5

>>> with open(from_file) as f:
...     content = f.read()

The with will make sure the file is closed.

🌐
GitHub
github.com › smicallef › spiderfoot › issues › 1820
sfcli: -e argument: AttributeError: 'str' object has no attribute 'close' · Issue #1820 · smicallef/spiderfoot
November 4, 2023 - # ./sfcli.py -e /tmp/asdf Traceback (most recent call last): File "/root/Desktop/spiderfoot/./sfcli.py", line 1422, in <module> s.cmdloop() File "/usr/lib/python3.11/cmd.py", line 132, in cmdloop line = self.stdin.readline() ^^^^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'readline' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/Desktop/spiderfoot/./sfcli.py", line 1424, in <module> cin.close() ^^^^^^^^^ AttributeError: 'str' object has no attribute 'close' Reactions are currently unavailable ·
Author   bcoles
Discussions

AttributeError: 'str' object has no attribute 'close'
From guppy...@gmail.com on May 27, 2012 06:37:07 I'm using the latest r1409 and I'm seeing this trackback: Traceback (most recent call last): File "C:\Python25\lib\asyncore.py", l... More on github.com
🌐 github.com
4
May 28, 2014
'Str' object has no attribute error?
The issue is that self.tasks is either a string or a list of strings. But you haven't shown where that is defined. More on reddit.com
🌐 r/learnpython
9
2
November 9, 2023
python - str object has no attribute 'close' - Stack Overflow
Im analyzing a text for word frequency and I am getting this error message after it is done: 'str' object has no attribute 'close' I've used the close() method before so I dont know what to do. H... More on stackoverflow.com
🌐 stackoverflow.com
python - Fixing "AttributeError: 'str' object has no attribute 'close'" when multithreading from file? - Stack Overflow
Getting a AttributeError: 'str' object has no attribute 'close' Tried closing file (still in code below), recoded twice. import urllib2 import csv import lxml from bs4 import BeautifulSoup from More on stackoverflow.com
🌐 stackoverflow.com
May 11, 2019
🌐
GitHub
github.com › giampaolo › pyftpdlib › issues › 208
AttributeError: 'str' object has no attribute 'close' · Issue #208 · giampaolo/pyftpdlib
May 28, 2014 - I'm using the latest r1409 and ...tp_queue[3].close() AttributeError: 'str' object has no attribute 'close' The line numbers may not match up exactly -- I've got two modifications that I've been using for quite some time (passing ...
Published   May 28, 2014
🌐
Reddit
reddit.com › r/learnpython › 'str' object has no attribute error?
r/learnpython on Reddit: 'Str' object has no attribute error?
November 9, 2023 -

I have some experience with programming in Java, C++, etc. and I am trying to write a simple "To-Do List" program to get used to Python. I'm running into the error: str object has no attribute "completed" when trying to iterate over the list of tasks, check their completion status, and display them.

Here are some relevant pieces of the program:

Constructor for the Task class

def __init__(self, task_name):

self.task_name = task_name

self.completed = False

In the ToDoList class (which holds a list of the task instances created by the user) this is the iteration throwing the error in question:

for idx, task in enumerate(self.tasks, start=1):

status = "Completed" if task.completed else "Incomplete"

print(f"{idx}. {task.task_name} - {status}")

I thought, potentially the problem lies in the fact that the enumerate function is grabbing the string value of the task instance, rather than the object itself, so maybe I can iterate over it the old fashioned way and get around it. So I tried it like this:

counter = 1

for task in self.tasks:

status = "Completed" if task.completed else "Incomplete"

print(f"{counter}. {task.task_name} - {status}")

counter += 1

Yet, it throws the same error. I know there is something I am missing or not understanding correctly here. What is it?

Thanks!

🌐
Esri Community
community.esri.com › t5 › arcgis-api-for-python-questions › str-object-has-no-attribute › td-p › 1053478
Solved: 'str' object has no attribute - Esri Community
September 14, 2021 - The clone_items function takes a list of Items. It seems like you are passing in the string item ids instead.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-attributeerror-object-has-no-attribute
How to fix AttributeError: object has no attribute - GeeksforGeeks
July 23, 2025 - To understand this error, we first have to know how to read the error message effectively. It typically consists of two parts: "AttributeError" and "Object has no attribute." The former indicates the type of error, and the latter suggests that the attribute we are trying to access does not exist for the object.
Find elsewhere
🌐
Brainly
brainly.com › engineering › college › what does "str object has no attribute" mean in python?
[FREE] What does "str object has no attribute" mean in Python? - brainly.com
In Python, the error message "AttributeError: 'str' object has no attribute" indicates that you are trying to access a method or attribute that does not exist for string objects.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-str-object-has-no-attribute
AttributeError: 'str' object has no attribute 'X in Python | bobbyhadz
April 8, 2024 - The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects.
🌐
Quora
quora.com › How-do-you-resolve-attributeerror-str-object-has-no-attribute-variables-Python-solutions
How to resolve 'attributeerror: 'str' object has no attribute 'variables'' (Python, solutions) - Quora
Fix the source of the string—load, instantiate, or look up the actual object—and avoid name shadowing so .variables is called on the correct type. ... RelatedHow do you resolve "attributeerror: 'dataframe' object has no attribute 'reshape'" (Python, Python 3.x, machine learning, deep learning, LSTM, development)?
🌐
GitHub
github.com › shaikhsajid1111 › twitter-scraper-selenium › issues › 63
AttributeError: 'str' object has no attribute 'close' · Issue #63 · shaikhsajid1111/twitter-scraper-selenium
February 20, 2023 - AttributeError: 'str' object has no attribute 'close'#63 · Copy link · ProgramerAnel · opened · on Feb 20, 2023 · Issue body actions ·
Author   ProgramerAnel
🌐
Python.org
discuss.python.org › python help
AttributeError: 'str' object has no attribute 'fetch' - Python Help - Discussions on Python.org
February 20, 2021 - I’m trying to get working the python code at the following website: After several days I’m still not able to succeed since it stucks giving the recurring error message AttributeError: ‘str’ object has no attribute 'fet…
🌐
Researchdatapod
researchdatapod.com › home › how to solve python attributeerror: ‘str’ object has no attribute ‘close’
How to Solve Python AttributeError: 'str' object has no attribute 'close' - The Research Scientist Pod
May 12, 2022 - You can solve this error by keeping the open() call separate from the read() call so that the file object and file contents are under different variable names. Then you can close the file once you have accessed the contents.
🌐
Stack Overflow
stackoverflow.com › questions › 78958525 › urllib3-connectionpool-py-line-1180-attributeerror-str-object-has-no-attribut
python 3.x - urllib3/connectionpool.py line 1180 AttributeError: 'str' object has no attribute 'close' - Stack Overflow
September 6, 2024 - Traceback (most recent call last): File "/home/spotparking/miniconda3/lib/python3.10/weakref.py", line 667, in _exitfunc f() File "/home/spotparking/miniconda3/lib/python3.10/weakref.py", line 591, in __call__ return info.func(*info.args, **(info.kwargs or {})) File "/home/spotparking/miniconda3/lib/python3.10/site-packages/urllib3/connectionpool.py", line 1180, in _close_pool_connections conn.close() AttributeError: 'str' object has no attribute 'close'
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 185328 › attributeerror-str-object-has-no-attribute-insert
python - AttributeError: 'str' object has no attribute ... [SOLVED] | DaniWeb
this is the error I'm getting for the code below: Error: 'str' object has no attribute 'insert' filetolist = FileReadToList("test.txt") print filetolist[0] def FileCountLines(s_filename): f = open(s_filename) filestring = f.read() count = operator.countOf(filestring, "\n") file.close(f) return count def FileReadToList(s_filename): f = open(s_filename) count = FileCountLines(s_filename) filestring = f.read() filestring.insert(0,count) file.close(f) return filestring
🌐
Django Forum
forum.djangoproject.com › using django › getting started
Getting 'str' object has no attribute 'objects' when using Model reference from setings.py - Getting Started - Django Forum
August 30, 2022 - Hi there, I have many Models, from which one is Workspace. I made a reference to this Model in settings.py to use it in otherfile.py, like below: #settings.py WORKSPACE_MODEL = "accounts.Workspace" Now, when I try to use it in otherfile.py like below: #otherfile.py from django.conf import settings Workspace = settings.WORKSPACE_MODEL print(Workspace.objects.all()) I get below error: 'str' object has no attribute 'objects' Error Full TraceBack is below: Traceback Switch to copy-and-pa...
🌐
Python Forum
python-forum.io › thread-30950.html
AttributeError: 'str' object has no attribute 'size'
Hi All, I'm doing a homework assignment and getting some errors when running the doctest. Everything seems to work fine when I manually enter data, but when I run the doctest, I am getting the same 3 errors. This is the code that I have written fo...