Alex Rivera | Logout

Python - 'str' object has no attribute 'close'

Asked 2012-08-25T02:11:54.753
17

I am having a great time trying to figure out why there doesn't need to be a closing attribute for this few lines of code I wrote:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

file_content = open(from_file).read()
new_file = open(to_file, 'w').write(file_content)

new_file.close()

file_content.close()

I read some things and other people's posts about this, but their scripts were a lot more complicated than what I'm currently learning, so I couldn't figure out why.

I am doing Learning Python the Hard Way and would appreciate any help.

Edit
Report

2 Answers

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()).

answered 2012-08-25T02:16:10.183
1

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.

answered 2012-08-25T02:17:53.593

Your Answer