When a file is opened using Python’s open()
function, it returns a file object. This object contains several attributes that provide information about the file and its state.
🔹 File Object Attributes
1️⃣ name
– File Name
Returns the name of the file.
file = open("example.txt", "w")
print(file.name) # Output: example.txt
file.close()
2️⃣ mode
– Access Mode
Returns the mode in which the file is opened ('r'
, 'w'
, 'a'
, etc.).
file = open("example.txt", "w")
print(file.mode) # Output: w
file.close()
3️⃣ closed
– File Close Status
Returns True
if the file is closed, otherwise False
.
file = open("example.txt", "w")
print(file.closed) # Output: False
file.close()
print(file.closed) # Output: True
4️⃣ readable()
– Check Read Permission
Returns True
if the file is readable.
file = open("example.txt", "r")
print(file.readable()) # Output: True
file.close()
5️⃣ writable()
– Check Write Permission
Returns True
if the file is writable.
file = open("example.txt", "w")
print(file.writable()) # Output: True
file.close()
6️⃣ encoding
– File Encoding Type
Returns the encoding format of the file (default is 'UTF-8'
).
file = open("example.txt", "w", encoding="utf-8")
print(file.encoding) # Output: utf-8
file.close()
7️⃣ seekable()
– Check If File Supports seek()
Returns True
if the file allows random access (i.e., moving the file pointer).
file = open("example.txt", "r")
print(file.seekable()) # Output: True
file.close()
8️⃣ fileno()
– File Descriptor
Returns the file descriptor number assigned by the OS.
file = open("example.txt", "w")
print(file.fileno()) # Output: Some integer (e.g., 3)
file.close()
✅ Useful for low-level system operations.
9️⃣ flush()
– Flush Buffer Data
Writes all buffered data to the file immediately.
file = open("example.txt", "w")
file.write("Hello, Python!")
file.flush() # Ensures data is written to the file
file.close()
✅ Useful when writing large files to ensure data is saved.
🔹 Example: Using All Attributes
with open("example.txt", "w", encoding="utf-8") as file:
print("File Name:", file.name)
print("Mode:", file.mode)
print("Encoding:", file.encoding)
print("Is Readable?", file.readable())
print("Is Writable?", file.writable())
print("Is Seekable?", file.seekable())
print("File Descriptor:", file.fileno())
print("Is Closed?", file.closed)
print("After closing, Is Closed?", file.closed)
🔹 Summary of File Object Attributes
Attribute | Description |
---|---|
name |
Returns the file name. |
mode |
Returns the access mode ('r' , 'w' , etc.). |
closed |
Returns True if the file is closed. |
readable() |
Returns True if the file is readable. |
writable() |
Returns True if the file is writable. |
encoding |
Returns the file encoding (e.g., 'utf-8' ). |
seekable() |
Returns True if seek() is supported. |
fileno() |
Returns the file descriptor number. |
flush() |
Forces writing data from buffer to file. |
Would you like a practical example, like monitoring file status while processing logs? 🚀
Leave a Reply