Can only one file be open at once? If no, does the file.close() method close all open files... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can only one file be open at once? If no, does the file.close() method close all open files...

Multiple files

11th Oct 2016, 2:28 PM
Paul Obasi
Paul Obasi - avatar
3 Answers
+ 2
No and no. There is an open files limit, but you're completely at liberty to leave open files all over the place because python will clean up after you. http://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important Try this in C++ and you'll lose data.
11th Oct 2016, 4:05 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
After answering the first time I noticed that Python supports directly opening handles (integer references rather than file objects). This is more 'low level' but importantly allows you to use commands to close a block of open files: https://docs.python.org/3/library/os.html Search for: os.closerange
21st Oct 2016, 7:25 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
I've got what you mean, in this example 'file' is a name of variable, you can open as much files as you want: a = open(some.txt, r) b = open(data.csv, rb) C = open(somedata.txt, wb) etc a.close Variable is now stuck to the file, till file is closed, closed files are removed from memory, and will be synced to disk(if will be write).
21st Oct 2016, 5:56 PM
Dmitrii Sky
Dmitrii Sky - avatar