User Tools

Site Tools


misc:code_snippets:python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
misc:code_snippets:python [2017/03/06 21:40] – mehr Beispielcode hinzugefügt saschamisc:code_snippets:python [2017/04/11 15:13] (current) – Fix sascha
Line 72: Line 72:
 with tempfile.TemporaryDirectory() as tmp_dir: with tempfile.TemporaryDirectory() as tmp_dir:
     pass  # do stuff     pass  # do stuff
 +</code>
 +
 +
 +==== Mittels Pipe übergebene Daten lesen ====
 +
 +<code python>
 +import sys
 +
 +# ensure the script only reads piped data and doesn't wait for user input
 +if not sys.stdin.isatty():
 +    lst = [l.strip() for l in sys.stdin.readlines() if not l.startswith('#')]
 +    print(lst)
 +</code>
 +
 +
 +==== Dateien aus einem Verzeichnis erhalten oder aus Datei lesen ====
 +
 +<code python>
 +import os
 +from os.path import expanduser, isdir, isfile, abspath, join as pjoin
 +
 +def get_files(path=/some/path):
 +    files = []
 +    path = expanduser(path)
 +
 +    if isdir(path):
 +        files = [pjoin(abspath(path), f) for f in os.listdir(path) if
 +                 (isfile(pjoin(path, f)) and f.lower().endswith('.ext'))]
 +    elif isfile(path):
 +        with open(path, 'r') as lst:
 +            files = [l.strip() for l in lst.readlines() if not l.startswith('#') and l.split()]
 +
 +    return files
 </code> </code>
  
misc/code_snippets/python.1488836429.txt.gz · Last modified: by sascha