Tricky Python Files & File Operations

Tricky Python Files & File Operations Interview Questions

What is the difference between 'r+' and 'w+' file modes?
'r+' opens for reading and writing (file must exist). 'w+' opens for reading and writing (creates/truncates file).
# 'r+' - File must exist, pointer at beginning
# 'w+' - Creates new file or truncates existing, pointer at beginning
How does seek() work with text files vs binary files?
In binary files, seek(offset) moves to exact byte position. In text files, offset must be 0 or value from tell() due to encoding issues (UTF-8 characters have variable byte length).
What happens if you don't close a file in Python?
Resource leak! Changes might not be written (buffered data). Memory issues with many open files. Use with statement for automatic closing:
with open('file.txt', 'r') as f:
    data = f.read()
# File automatically closed here
What's the difference between read(), readline(), and readlines()?
read() reads entire file as string.
readline() reads one line at a time.
readlines() reads all lines into list.
Warning: read() on large files can cause memory issues!
How to read a file backwards in Python?
Read entire file and reverse, or use seek() with negative offsets in binary mode:
with open('file.txt', 'rb') as f:
    f.seek(0, 2) # Go to end
    while f.tell() > 0:
        f.seek(-1, 1) # Move back 1 byte
        print(f.read(1).decode())
        f.seek(-1, 1) # Move back again
What is the difference between flush() and close()?
flush() writes buffered data to disk but keeps file open. close() writes buffered data AND releases system resources. Data can be lost if program crashes between flush() and close().
How to handle file encoding issues in Python?
Specify encoding parameter: open('file.txt', 'r', encoding='utf-8'). Common encodings: UTF-8, ASCII, Latin-1. Use errors='ignore' or errors='replace' to handle decoding errors.
What happens when you write to a file opened in append mode multiple times?
Each write appends to the end, regardless of seek position. Even if you use seek(0), writing will still append to end in 'a' or 'a+' modes.
How to delete a file that's currently open?
On Windows: Cannot delete open files. On Unix/Linux: Can delete (file descriptor remains). The file persists until all handles close. Use os.remove() after closing.
What is the file object's buffer size and how to change it?
Default buffer size is 8KB. Change with buffering parameter:
# 0 = no buffering (binary only)
# 1 = line buffering (text only)
# n = buffer size in bytes
open('file.txt', 'r', buffering=1024) # 1KB buffer
How to check if a file exists without opening it?
Use os.path.exists() or Path.exists() from pathlib. BUT race condition possible! File could be deleted between check and open. Better to use try-except:
What is the difference between 'x' and 'w' modes?
'x' (exclusive creation) fails if file exists. 'w' truncates/overwrites if file exists. 'x' prevents accidental overwrites:
How to read a file in chunks efficiently?
Use a loop with specified chunk size:
chunk_size = 1024 # 1KB
with open('large_file.bin', 'rb') as f:
    while chunk := f.read(chunk_size):
        process(chunk)
What happens when you write Unicode characters to a binary file?
You must encode them first! Binary files expect bytes, not strings:
with open('file.bin', 'wb') as f:
    f.write("Hello 𝄞".encode('utf-8')) # Encode string to bytes
How to lock a file for exclusive access?
Use fcntl (Unix) or msvcrt (Windows) for advisory locks. File locking is OS-dependent and not 100% reliable across all systems.
What is the difference between tell() and seek()?
tell() returns current file position. seek(offset, whence) moves to position. Whence: 0=start, 1=current, 2=end.
How to handle CSV files with inconsistent quoting?
Use csv module with quoting=csv.QUOTE_ALL or quoting=csv.QUOTE_NONE. Handle escape characters properly:
What is memory-mapped file I/O (mmap)?
mmap maps file directly to memory. Allows random access like a bytearray. Efficient for large files. Use with mmap module.
How to create a temporary file that auto-deletes?
Use tempfile.TemporaryFile() or tempfile.NamedTemporaryFile(delete=True). Files are deleted when closed or program exits.
What is the difference between os.remove() and os.unlink()?
They're identical! os.remove() and os.unlink() do exactly the same thing. unlink is the Unix system call name.
Note: These tricky questions test deep understanding of Python file operations. Key concepts: file modes, buffering, encoding, resource management, and edge cases. Always use context managers (with statement) for safe file handling!
Tricky Python Files & File Operations Next