Skip to content
Advertisement

Python – ‘str’ object has no attribute ‘close’

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement