Using context managers to open files.
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 4 Sep 2018 17:45:37 +0000 (19:45 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 4 Sep 2018 17:45:37 +0000 (19:45 +0200)
seewasser.py

index b8a23b6..600bf3d 100755 (executable)
@@ -57,21 +57,17 @@ def readsensor(sensor_id):
 
 def writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value):
     # Schreiben des csv-files
-    file = open(os.path.expanduser(config.get("csv", "filename")), "a", newline = "")
-    writer = csv.writer(file, dialect = "excel")
-    writer.writerow([timestamp.strftime("%Y-%m-%d %H:%M"), sensor_id, sensor_name, "{:.1f}".format(value)])
-
-    file.close()
+    with open(os.path.expanduser(config.get("csv", "filename")), "a", newline = "") as file:
+        writer = csv.writer(file, dialect = "excel")
+        writer.writerow([timestamp.strftime("%Y-%m-%d %H:%M"), sensor_id, sensor_name, "{:.1f}".format(value)])
 
 
 def readcsvfile(csvfile):
-    file = open(csvfile, "r", newline="")
-    reader = csv.DictReader(file, dialect = "excel", fieldnames=("timestamp", "sensor_id", "sensor_name", "value"))
-    records = []
-    for row in reader:
-        records.append(row)
-
-    file.close()
+    with open(csvfile, "r", newline="") as file:
+        reader = csv.DictReader(file, dialect = "excel", fieldnames=("timestamp", "sensor_id", "sensor_name", "value"))
+        records = []
+        for row in reader:
+            records.append(row)
     return records