Python - 'str' object has no attribute 'close'
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.
When you do file_content = open(from_file).read()
, you set file_content
to the contents of the file (as read by read
). You can't close this string. You need to save the file object separately from its contents, something like:
theFile = open(from_file)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
You have a similar problem with new_file
. You should separate the open(to_file)
call from the write
.