|
|
|
---
|
|
|
|
title: Python 3 cheatsheet
|
|
|
|
tags: [tutorial, python3, python, cheatsheet]
|
|
|
|
updated: 2021-09-13 14:07:00
|
|
|
|
description: A series of instructions in Python I use frequently on several projects
|
|
|
|
---
|
|
|
|
|
|
|
|
## Table of contents
|
|
|
|
|
|
|
|
<!--TOC-->
|
|
|
|
|
|
|
|
- [Table of contents](#table-of-contents)
|
|
|
|
- [Introduction](#introduction)
|
|
|
|
- [pathlib](#pathlib)
|
|
|
|
- [Files](#files)
|
|
|
|
- [Paths](#paths)
|
|
|
|
- [PyYAML](#pyyaml)
|
|
|
|
|
|
|
|
<!--TOC-->
|
|
|
|
|
|
|
|
## Introduction
|
|
|
|
|
|
|
|
This is a list of instructions I use frequently in:
|
|
|
|
|
|
|
|
- [automated-tasks](https://blog.franco.net.eu.org/software/#automated-tasks)
|
|
|
|
- [fattura-elettronica-reader](https://blog.franco.net.eu.org/software/#fattura-elettronica-reader)
|
|
|
|
- [fpyutils](https://blog.franco.net.eu.org/software/#fpyutils)
|
|
|
|
- [md-toc](https://blog.franco.net.eu.org/software/#md-toc)
|
|
|
|
|
|
|
|
## pathlib
|
|
|
|
|
|
|
|
### Files
|
|
|
|
|
|
|
|
| Description | Code | Imports |
|
|
|
|
|-------------|-------------------------------------------------|---------|
|
|
|
|
| new file | `pathlib.Path(shlex.quote(path: str)).touch(0o700, exist_ok=True)` | `import pathlib, shlex` |
|
|
|
|
| remove file | `pathlib.Path(shlex.quote(path: str)).unlink(missing_ok=True)` | `import pathlib, shlex` |
|
|
|
|
| new directory | `pathlib.Path(shlex.quote(path: str)).mkdir(mode=0o700, parents=True, exist_ok=True)` | `import pathlib, shlex` |
|
|
|
|
|
|
|
|
### Paths
|
|
|
|
|
|
|
|
| Description | Code | Imports |
|
|
|
|
|-------------|-------------------------------------------------|---------|
|
|
|
|
| get last path component from url | `pathlib.Path(urllib.parse.urlsplit(url: str).path).name` | `import pathlib, urllib` |
|
|
|
|
| get relative path | `pathlib.Path(shlex.quote(path: str)).name` | `import pathlib, shlex` |
|
|
|
|
| get full path | `str(pathlib.Path(shlex.quote(directory: str), shlex.quote(file: str)))` | `import pathlib, shlex` |
|
|
|
|
| remove file extension | `pathlib.Path(shlex.quote(path: str)).stem` | `import pathlib, shlex` |
|
|
|
|
| get file extension | `pathlib.Path(shlex.quote(path: str)).suffix` | `import pathlib, shlex` |
|
|
|
|
| get the path of a configuration file | `configuration_file = shlex.quote(sys.argv[1])` | `import shlex, sys` |
|
|
|
|
|
|
|
|
## PyYAML
|
|
|
|
|
|
|
|
| Description | Code | Imports |
|
|
|
|
|-------------|-------------------------------------------------|---------|
|
|
|
|
| load a YAML file | `config = yaml.load(open(file: str, 'r'), Loader=yaml.SafeLoader)` | `import yaml` |
|