0
Opening and closing files using the same variable?
So in one of the lessons on opening and closing diles, the example given was: f = open("filename.txt") print(f.read()) f.close() Now, if I'm not mistaken, isnt f a veriable that was assigned the function of opening the given file? If its function is to open the file, how come it also functions to read and then close the file?
4 Answers
+ 4
f is just a name. You could give it to any sort of object, like a number or a string.
f = 4
f = 'hey'
With open() you create a file object, and you stick the name sticker f on it.
And as long as you don't use f for something else, you can now access that file object via f and use its methods.
+ 1
f is a file object.
You probably know a list object: it can do several things, like appending, sorting or deleting.
You would also create that with =, like:
list_ = [1, 2, 3]
list_.append(4)
list_.remove(2)
...
And a file object has among others a method to read it, and one to close it.
+ 1
I see, you're not assigning the f to the action of opening, you're just assigning it to a file to be opened. Thank you for explaining!
0
Ah, so f by default refers to a file action without the f having to be defined?