Dateien¶
In [ ]:
fp = open("../uebungen/salaries.txt", encoding="utf-8")
content = fp.read()
print(type(content))
<class 'str'>
In [ ]:
fp = open("../uebungen/salaries.txt", "rb")
content = fp.read()
print(type(content))
text = content.decode("utf-8")
print(type(text))
<class 'bytes'> <class 'str'>
In [ ]:
fp = open("../uebungen/salaries.txt", mode="r")
line = fp.readline()
print(repr(line))
'Anna: 2000\n'
In [ ]:
fp = open("../uebungen/salaries.txt", mode="r", encoding="utf-8")
while True:
line = fp.readline()
if not line:
break
print(line, end="")
Anna: 2000 Mark: 3000 Judith: 3500 Thomas: 2500 Barbara: 3000 Elke: 3300 Michael: 2800 Johann: 2000
In [ ]:
fp = open("../uebungen/salaries.txt", mode="r", encoding="utf-8")
lines = fp.readlines()
print(type(lines))
print(lines)
<class 'list'> ['Anna: 2000\n', 'Mark: 3000\n', 'Judith: 3500\n', 'Thomas: 2500\n', 'Barbara: 3000\n', 'Elke: 3300\n', 'Michael: 2800\n', 'Johann: 2000\n']
In [ ]:
fp = open("../uebungen/salaries.txt", mode="r", encoding="utf-8")
for line in fp:
print(line, end="")
Anna: 2000 Mark: 3000 Judith: 3500 Thomas: 2500 Barbara: 3000 Elke: 3300 Michael: 2800 Johann: 2000
In [ ]:
fp = open("../uebungen/salaries.txt", mode="r", encoding="utf-8")
for line in fp:
print(line, end="")
fp.close()
Anna: 2000 Mark: 3000 Judith: 3500 Thomas: 2500 Barbara: 3000 Elke: 3300 Michael: 2800 Johann: 2000
In [ ]:
lines = open("../uebungen/salaries.txt", encoding="utf-8").readlines()
In [ ]:
with open("../uebungen/salaries.txt") as fp:
for line in fp:
print(line, end="")
Anna: 2000 Mark: 3000 Judith: 3500 Thomas: 2500 Barbara: 3000 Elke: 3300 Michael: 2800 Johann: 2000
In [ ]:
# Pseudo Code! Nicht ausführbar
fp = open("../uebungen/salaries.txt")
ctx = new_context(fp)
fp.open_context(ctx)
# code block
fp.end_context(ctx)
In [ ]:
# Pseudo Code! Nicht ausführbar
try:
fp = open("datei")
except FileNotFoundError:
# code
except OSError:
# code
In [ ]:
import json
data = json.loads("[1, 2, 3]")
print(data)
d1 = {"foo": 42, "bar": 23}
print(json.dumps(d1))
d2 = {"foo": 42, "bar": 23, "baz": [1, 2, 3]}
print(json.dumps(d2))
l = [d1, d2]
print(json.dumps(l))
[1, 2, 3] {"foo": 42, "bar": 23} {"foo": 42, "bar": 23, "baz": [1, 2, 3]} [{"foo": 42, "bar": 23}, {"foo": 42, "bar": 23, "baz": [1, 2, 3]}]
In [ ]:
data = {"foo": 42, "bar": 23, "baz": [1, 2, 3]}
with open("data.json", "w") as fp:
json.dump(data, fp)
In [ ]:
with open("data.json") as fp:
data2 = json.load(fp)
assert data == data2, "Not equal"