Fancier Output Formatting
There are three main ways to format output:- f-strings: Formatted string literals
- str.format(): The string format method
- Manual formatting: String slicing and concatenation
Formatted String Literals (f-strings)
Prefix strings withf or F and include expressions in {}:
The str.format() Method
Basic usage:**:
Manual String Formatting
String methods for formatting: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
Useopen() to work with files:
File Modes
Using with Statements
Thewith keyword ensures files are properly closed:
with, you must manually close files:
Methods of File Objects
Reading Files
Read entire file:Writing Files
Write a string:write() returns the number of characters written.File Positioning
Get current position:whence=0: From beginning (default)whence=1: From current positionwhence=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)
