Python provides built-in functions to interact with files on the filesystem. The standard workflow involves opening a file, performing read or write operations, and then closing it.
# Basic file handling using open()
f = open(r'D:\Python27\day10\a.txt', 'r', encoding='utf-8')
content = f.read()
print(content)
f.close()
A more robust approach uses the with statement, which automatical closes the file even if an error occurs:
with open('a.txt', 'r', encoding='utf-8') as file_handle:
data = file_handle.read()
print(data)
File Access Modes
Common text-based modes include:
'r': Read-only (default). Fails if the file doesn’t exist.'w': Write-only. Creates a new file or truncates an existing one.'a': Append-only. Writes data at the end of the file; creates the file if missing.
Example using write mode:
with open('output.txt', 'w', encoding='utf-8') as writer:
writer.write('Line 1\n')
writer.write('Line 2\n')
Append mode preserves existing content:
with open('log.txt', 'a', encoding='utf-8') as appender:
appender.write('New log entry\n')
Reading Methods
Different methods support various reading strategies:
.read(): Loads entire file content as a single string..readline(): Reads one line at a time..readlines(): Returns a list where each element is a line.- Iterating directly over the file object reads line-by-line efficiently:
with open('large_file.txt', 'r', encoding='utf-8') as reader:
for line in reader:
process(line.strip())
This last method avoids loading the whole file into memory, making it suitable for large files.
Text vs Binary Modes
Text mode (t, default) handles string data and requires an encoding parameter:
with open('data.txt', 'rt', encoding='utf-8') as txt_file:
content = txt_file.read()
Binary mode (b) works with bytes and does not accept an encoding:
with open('image.png', 'rb') as bin_file:
raw_bytes = bin_file.read()
Binary mode is necessary for non-text files like images, executables, or serialized data.