The snippet library.
Small, practical examples. Search by task or narrow things down below.
Append a line to a file
Add a new line to the end of a text file without replacing its existing contents. Append mode also creates the file if it does not exist.
file✓ Tested
Create nested folders
Create a folder and any missing parent folders in one call. Running the code again is safe when the folder already exists.
directory✓ Tested
List files in a folder
List the names of regular files in a folder in alphabetical order, excluding subdirectories.
directory✓ Tested
Read a text file
Open a UTF-8 text file and read its contents. A context manager closes the file automatically, even if reading fails.
file✓ Tested
Write a text file
Save a string to a UTF-8 text file and close the file automatically when the write finishes.
file✓ Tested