Skip to main content
Python provides several ways to present output and read input. This guide covers formatted output, file operations, and JSON serialization.

Fancier Output Formatting

There are three main ways to format output:
  1. f-strings: Formatted string literals
  2. str.format(): The string format method
  3. Manual formatting: String slicing and concatenation

Formatted String Literals (f-strings)

Prefix strings with f or F and include expressions in {}:
Format specifiers:
Column alignment:
Conversion modifiers:
Self-documenting expressions:

The str.format() Method

Basic usage:
Positional arguments:
Keyword arguments:
Accessing dictionary values:
Or unpack with **:
Aligned columns:

Manual String Formatting

String methods for formatting:
Zero-padding:

Old String Formatting

The % operator can also format strings:
While % formatting still works, f-strings and str.format() are more powerful and easier to read.

Reading and Writing Files

Use open() to work with files:

File Modes

Always specify encoding="utf-8" when opening text files to ensure consistent behavior across platforms.

Using with Statements

The with keyword ensures files are properly closed:
Without with, you must manually close files:
Failing to close files can result in data loss. Always use with statements or explicitly call f.close().

Methods of File Objects

Reading Files

Read entire file:
Read a single line:
Loop over lines (efficient):
Read all lines into a list:

Writing Files

Write a string:
write() returns the number of characters written.
Write other types:

File Positioning

Get current position:
Change position:
seek() parameters:
  • whence=0: From beginning (default)
  • whence=1: From current position
  • whence=2: From end of file

Saving Structured Data with JSON

JSON (JavaScript Object Notation) is perfect for serializing Python data:

Writing JSON to a File

Reading JSON from a File

JSON files must be encoded in UTF-8. Always use encoding="utf-8" when opening JSON files.

JSON Limitations

  • Handles lists and dictionaries well
  • Arbitrary class instances require extra work
  • For Python-specific serialization, consider pickle (but it’s insecure with untrusted data)
Security Note: The pickle module can execute arbitrary code when deserializing data. Never unpickle data from untrusted sources.

Complete Example

Here’s a complete example combining file I/O and JSON:

Next Steps

You now understand file I/O and data serialization. Next, learn how to handle Errors and Exceptions gracefully in your programs.