This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
python_cheatsheet [2018/06/01 18:45] nasikimi created |
python_cheatsheet [2020/04/02 17:19] (current) nasikimi |
||
---|---|---|---|
Line 8: | Line 8: | ||
===== Snippets ===== | ===== Snippets ===== | ||
+ | |||
+ | === Une version du find === | ||
+ | <code python> | ||
+ | import os | ||
+ | |||
+ | path = 'c:\\projects\\hc2\\' | ||
+ | |||
+ | files = [] | ||
+ | # r=root, d=directories, f = files | ||
+ | for r, d, f in os.walk(path): | ||
+ | for file in f: | ||
+ | if '.txt' in file: | ||
+ | files.append(os.path.join(r, file)) | ||
+ | |||
+ | for f in files: | ||
+ | print(f) | ||
+ | </code> | ||
=== Retourner les lignes non-vides d'un fichier === | === Retourner les lignes non-vides d'un fichier === | ||
Line 19: | Line 36: | ||
URL = "https://url_bidon.com/topic={id}" | URL = "https://url_bidon.com/topic={id}" | ||
URL.format(id=id_bidon) | URL.format(id=id_bidon) | ||
+ | </code> | ||
+ | |||
+ | === Rechercher un fichier dans une arborescence (tree) === | ||
+ | <code python> | ||
+ | import os | ||
+ | |||
+ | def find(name, path): | ||
+ | for root, dirs, files in os.walk(path): | ||
+ | if name in files: | ||
+ | result = os.path.join(root, name) # first match | ||
+ | result = result.append(os.path.join(root, name)) # all matches (result is a list) | ||
+ | </code> | ||
+ | |||
+ | ===== Factorisation ===== | ||
+ | |||
+ | === Affecter un booléen en fonction d'une valeur === | ||
+ | <code python> | ||
+ | # Plutôt que de faire... | ||
+ | if x < 0: | ||
+ | bool = True | ||
+ | else: | ||
+ | bool = False | ||
+ | | ||
+ | # ... on peut faire... | ||
+ | bool = x < 0 | ||
</code> | </code> | ||