Python provides robust file handling capabilities, allowing you to create, read, update, and delete files. Here’s a breakdown of the essential file handling operations:
Opening a File
Python uses the open() function to open files, which returns a file object.
Syntax:
file = open("filename", "mode")
Common file modes include:
“r”– Read (default): Opens the file for reading; error if the file does not exist.
“w”– Write: Opens the file for writing, creates a new file if it doesn’t exist, or truncates the file if it exists.
“a”–Append: Opens the file for appending; creates the file if it doesn’t exist.
“r+”– Read and Write: Opens the file for both reading and writing.
Python File Handling – Interview Questions
Q 1: What is file handling in Python?
Ans: File handling allows reading from and writing to files using Python code
Q 2: Which function opens a file in Python?
Ans: The open() function is used to open files.
Q 3: What are common file modes in Python?
Ans: 'r' for read, 'w' for write, 'a' for append, and 'rb' for binary read.
Q 4: How do you close a file?
Ans: Using the close() method or the with statement automatically.
Q 5: Why is file handling important?
Ans: It allows persistent storage of data and reading/writing operations.