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()).
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()).
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.
AttributeError: 'str' object has no attribute 'close'
'Str' object has no attribute error?
python - str object has no attribute 'close' - Stack Overflow
python 3.x - urllib3/connectionpool.py line 1180 AttributeError: 'str' object has no attribute 'close' - Stack Overflow
Videos
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!
You didn't save a reference to the file handle. You opened the file, read its contents, and saved the resulting string. There's no file handle to close. The best way to avoid this is to use the with context manager:
def main():
with open("catinhat.txt") as f:
text=f.read()
...
This will close the file automatically after the with block ends, without an explicit f.close().
That is because your variable text has a type of string (as you are reading contests from a file).
Let me show you the exact example:
>>> t = open("test.txt").read()
#t contains now 'asdfasdfasdfEND' <- content of test.txt file
>>> type(t)
<class 'str'>
>>> t.close()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'
If you use an auxiliary variable for the open() function (which returns a _io.TextIOWrapper), you can close it:
>>> f = open("test.txt")
>>> t = f.read() # t contains the text from test.txt and f is still a _io.TextIOWrapper, which has a close() method
>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.close() # therefore I can close it here
>>>