Python File Handling: Reading/Writing Text, CSV & JSON Files
1. How do you read and write text files in Python?
Q: How to read/write text files?
Reading Text Files: Use the open() function to access a file's contents, then read using methods like read(), readline(), or readlines().
Writing Text Files: Use open() with a write mode, then write using write() or writelines().
Key Methods:
file.read(size): Reads entire file or up tosizebytes.file.readline(): Reads one line.file.readlines(): Reads all lines into a list.file.write(string): Writes a string.file.writelines(lines): Writes a list of strings.
Use Case: Storing logs, reading configuration files, or saving user data.
2. Can you give an example of reading and writing text files?
# Reading and writing text files
# Writing to a file
with open('output.txt', 'w') as file:
file.write("Hello, Python!\n")
file.writelines(["Line 1\n", "Line 2\n"])
# Reading from a file
with open('output.txt', 'r') as file:
content = file.read()
print("Full content:")
print(content)
# Reading line by line
with open('output.txt', 'r') as file:
lines = file.readlines()
print("Lines as list:")
print(lines)
Output:
Full content:
Hello, Python!
Line 1
Line 2
Lines as list:
['Hello, Python!\n', 'Line 1\n', 'Line 2\n']
3. What is the with statement in Python file handling?
Q: What is the with statement?
with Statement: A context manager that ensures files are properly opened and closed, even if an error occurs.
Syntax:
with open('file.txt', mode) as file:
# File operations
Benefits:
- Automatically closes the file after operations.
- Handles exceptions gracefully.
- Simplifies code compared to manual
file.close().
Use Case: Safe file operations, preventing resource leaks.
4. Can you give an example of the with statement?
# with statement example
try:
with open('data.txt', 'w') as file:
file.write("Sample data\n")
print("File written successfully")
with open('data.txt', 'r') as file:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError as e:
print(f"Error: {e}")
Output:
File written successfully
File content:
Sample data
5. What are file modes in Python?
Q: What are file modes?
File Modes: Specify how a file is opened in the open() function.
Text Modes:
'r': Read (default, raises error if file doesn't exist).'w': Write (creates/overwrites file).'a': Append (adds to end, creates if doesn't exist).'r+': Read and write (file must exist).'w+': Write and read (creates/overwrites file).'a+': Append and read (creates if doesn't exist).
Binary Modes: Add b (e.g., 'rb', 'wb') for binary files (e.g., images, CSVs in some cases).
Use Case: Choosing the right mode for reading, writing, or appending data.
6. Can you give an example of different file modes?
# File modes example
# Write mode (w)
with open('modes.txt', 'w') as file:
file.write("Initial content\n")
# Append mode (a)
with open('modes.txt', 'a') as file:
file.write("Appended content\n")
# Read mode (r)
with open('modes.txt', 'r') as file:
print("Read mode content:")
print(file.read())
# Read and write mode (r+)
with open('modes.txt', 'r+') as file:
file.write("Updated")
file.seek(0) # Move to start
print("Read after r+ write:")
print(file.read())
# Binary mode (wb, rb)
with open('binary.bin', 'wb') as file:
file.write(b"Binary data")
with open('binary.bin', 'rb') as file:
print("Binary content:")
print(file.read())
Output:
Read mode content:
Initial content
Appended content
Read after r+ write:
Updated content
Appended content
Binary content:
b'Binary data'
7. How do you handle CSV and JSON files in Python?
Q: How to handle CSV and JSON?
CSV Files: Use the csv module to read/write comma-separated value files.
Methods: csv.reader, csv.writer, csv.DictReader, csv.DictWriter.
JSON Files: Use the json module to read/write JavaScript Object Notation data.
Methods: json.load() (read file), json.dump() (write file), json.loads() (parse string), json.dumps() (create string).
Use Case: Processing structured data (e.g., datasets, configuration files).
8. Examples of CSV and JSON handling + Best Practices
Q: Best practices for file handling?
- Always use
with open(...)to auto-close files. - Specify encoding:
open(..., encoding='utf-8'). - Handle exceptions (
FileNotFoundError,IOError). - Use
csvmodule for CSV to handle quoting/escaping. - Use
jsonfor structured data interchange. - Avoid hardcoding file paths; use
os.pathorpathlib.