File I/O (Input/Output) in Python
File I/O is a fundamental operation for working with data.
Python makes it easy to read from and write to text files.
The built-in open() function is used to open a file, and you can then use file object methods to read or write data.
When done, the file should be closed to free resources—best handled using a with statement for automatic cleanup.
Opening a File
To open a file, use:
open(filename, mode)
Mode options:
-
'r'→ Reading (default mode, if not specified) -
'w'→ Writing (creates a new file or truncates an existing one) -
'a'→ Appending (adds to end of file without truncating) -
'x'→ Exclusive creation (fails if file exists — less common in basics)
Example:
file = open("notes.txt", 'r') # open for reading
# ... use file.read() or other methods ...
file.close()
Using with for Automatic Closing
with open("notes.txt", 'r') as f:
content = f.read()
# file is automatically closed after the indented block
-
Ensures proper closing even if an error occurs.
-
Recommended pattern in most cases.
Reading from a Text File
Python file objects provide multiple methods:
-
f.read()→ Entire file as a single string. -
f.readline()→ One line (up ton). -
f.readlines()→ All lines in a list of strings.
You can also iterate over the file object directly:
Example: Read Entire File
with open("example.txt", 'r') as f:
data = f.read()
print(data)
Example: Read Line by Line
with open("example.txt", 'r') as f:
for line in f:
print(line.strip()) # removes newline
Example: Using readline() in a Loop
with open("example.txt", 'r') as f:
while True:
line = f.readline()
if not line:
break
print(line.strip())
Writing to a Text File
Modes for writing:
-
'w'→ Overwrite or create new file -
'a'→ Append to file
Example: Write New File
new_content = "Hello, world!nThis is a new file."
with open("output.txt", 'w') as f:
f.write(new_content)
Example: Write Multiple Lines
with open("numbers.txt", 'w') as f:
for i in range(5):
f.write(f"Line {i}n")
Example: Append to File
with open("output.txt", 'a') as f:
f.write("Appending a new line.n")
Flushing & Closing
-
Exiting a
withblock automatically flushes and closes the file. -
If not using
with(not recommended), call:f.flush() f.close()
Encoding Note
-
Default encoding is UTF-8 (works for most text).
-
To use another encoding:
open("file.txt", 'r', encoding='utf-16')
