Python - Closing files opened with the "x" attribute. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python - Closing files opened with the "x" attribute.

I have a code in which I need to create a file. I have these 2 ways in my mind: 1. open("a.txt", "x") 2. k = open("a.txt", "x") k.close() Which should I use? Will there be a problem if I don't store and close the file-descriptor (or a class, here) returned by open()?

4th May 2021, 6:11 AM
Calvin Thomas
Calvin Thomas - avatar
5 Answers
+ 1
The 'x' descriptor open a file in write mode. but it's particularity is its create a file only if that file does not exist , if it does it will raise a FileExistError. every time you open a file, no matter what descriptor you are using it's will take space in memory. so the best practice is to always close the file when you're done with it, this way the allocated memory will be freed and use for another things further reading https://alexwlchan.net/2016/03/exclusive-create-JUMP_LINK__&&__python__&&__JUMP_LINK/
4th May 2021, 7:28 AM
Alpha Diallo
Alpha Diallo - avatar
+ 2
To close a file first you need to keep a reference to it so the second is what you should go with. Or you can use a context manager to handle closing automatically. with open ('a.txt', 'x') as fp: # statements fp will be a ref to the file
4th May 2021, 6:24 AM
Alpha Diallo
Alpha Diallo - avatar
+ 1
Alpha Diallo Thanks for the helpful explanation.
4th May 2021, 8:39 AM
Calvin Thomas
Calvin Thomas - avatar
0
Alpha Diallo I see, but is there a problem if I don't close that single file-descriptor, as I haven't used any modes like read/write? I mean, the operating system is just creating the file, and the file pointer is useless now. Then why do I have to close it, or, why in the first place does the operating system need to create a file-descriptor for just creating a file, without doing any operations on it?
4th May 2021, 6:51 AM
Calvin Thomas
Calvin Thomas - avatar
0
We are together in this
4th May 2021, 8:51 AM
Alpha Diallo
Alpha Diallo - avatar