Python - str object has no close attribute

I'm having a great time trying to figure out why I don't need a closing attribute for these few lines of code that 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 something about this and other people's posts, but their scripts were much more complicated than what I am currently studying, so I could not understand why.

I am doing Python Learning the hard way and would appreciate any help.

+13
source share
3 answers

file_content - a string variable containing the contents of the file - it has nothing to do with the file. The file descriptor that you open with open(from_file) closes automatically: file sessions are closed after file objects exit the scope (in this case, immediately after .read() ).

+11
source

open(...) returns a link to a file object that calls read , which reads a file, returns a string object, calls write to it, returns None , none 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. 

Here are some ways to fix this:

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

or with python> = 2.5

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

with will make sure the file is closed.

+3
source

When you do file_content = open(from_file).read() , you set file_content to the contents of the file (as read read ). You cannot close this line. You need to save the file separately from its contents, for example:

 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 must separate the open(to_file) call from write .

+1
source

Source: https://habr.com/ru/post/923722/


All Articles