from IPython.display import HTML
HTML(open("notes.css", "r").read())
print()
Function¶sep
end
file
flush
print(1,2,3)
print(4, 5, 6)
print(1, "spam", (1,2), set(), { 'z':42 }, sep=", ", end="; ")
print("this is on the same line")
import time
print("waiting ... ", end="", flush=False)
time.sleep(10)
print("done")
basic I/O abstraction
predefined streams (a la POSIX)
You can import
these from sys
:
stdin
(or cin
in C++)stdout
(or cout
in C++)stderr
(or cerr
in C++)useful builtin stream function
next(stream)
%%sh
wc -l words.txt
f = open("words.txt")
for i in range(4):
print(next(f), end="")
while True:
word = next(f)
word
ctLines = 0
for line in open("words.txt"):
ctLines += 1
ctLines
read()
readline()
readlines()
write()
writeline()
writelines()
seek()
tell()
wholeFile = open("Makefile").read()
wholeFile
open("copiedFile", "w").write(wholeFile)
f = open("Makefile")
lines = f.readlines()
lines[4]
lines[1]
io
Module¶import io
io.DEFAULT_BUFFER_SIZE
open()
Function¶mode
(similar to stdio)r
": (default): readable text filer+
": readable/writeable text filew
": writeable text file created from scratcha
": writeable text file opened for appendingb
" to any of these read binary (unencoded) databuffering
encoding
file
object, but that class no longer existsclose()
method, but you almost never need its = "abcdef\n"
f = open("foo.txt", "w")
print(f)
f.write(s)
f.close()
s = b"abcdef\n"
f = open("foo.txt", "wb")
print(f)
f.write(s)
f.close()
s = "abcdef\n"
f = open("foo.txt", "w")
print(s, file=f, end="")
f.close()
We can copy a file with a single statement:
open("bar.txt", "wb").write(open("foo.txt", "rb").read())
Here's the effect of the "b
" flag:
rResult = open("foo.txt", "r").read()
print(" For file opened with 'r', read() returns:", type(rResult))
rbResult = open("foo.txt", "rb").read()
print("The same file opened with 'rb', read() returns:", type(rbResult))
hexwords
¶The file "words.txt
" contains a list of words, one per line. The goal is to find all pairs of words in the file that, when concatenated, form a legal 32-bit (8 hex digit) hexadecimal number, like "added fee". This means the words can only use letters "a" through "f".
# Build the list "hexWords[]" containing only words made from hex digits a-f
hexWords = []
for line in open('words.txt'):
# remove trailing `\n` from 'line'
line = line.rstrip()
if set(line) <= set('abcdef'): # We're intentionally ignoring upper case A-F
hexWords.append(line)
# no-prize challenge:
# Can you write the above as a single statement using a comprehension?
# Compare each pair of hexWords. If their combined length is 8, print them.
# (Can you think of a faster way to do this?)
count = 0
for hexWord0 in hexWords:
for hexWord1 in hexWords:
if len(hexWord0) + len(hexWord1) == 8:
print(hexWord0, hexWord1, end=' ')
count += 1
if count % 5 == 0:
print()
input()
Function¶text = input("What is the air speed velocity of an unladen swallow?")
print(f"user entered: \"{text}\"")
text
json
Module¶JSON is "JavaScript Object Notation", borrowed from the JavaScript language. It's a popular alternative to HTML and very well suited to Python.
import json
from pprint import pprint
struct = ( {
"red": 0,
"green": 1,
"blue": 2,
1: "a",
-2: "stuff",
3.1: (1, 2, 3)
},
[ ],
( -1, 0, "a string" )
)
# json.dumps() converts an object to a JSON string.
result = json.dumps(struct)
result
pprint(json.loads(result))
Note that all of the dictionary keys have been converted to strings. Although Python allows non-string keys, JSON does not. In fact, these are "objects", not dictionaries, in JSON. This means that you can't always count on loads(dumps(x)) == x
. Oh well.
json
can do prettyprinting. Unlike HTML, this does not change the semantics.
print(json.dumps(struct,
indent=4 # indent 4 spaces per level
))
Another few things about JSON:
Tuples are converted to lists, which JSON calls "arrays".
Sets are not allowed (so convert them to lists before dump
ing).
json.dump()
¶json.dump()
writes an object to a file in JSON format.outputFile = open("saved.json", "w")
json.dump(struct, outputFile)
outputFile.close()
# %load saved.json
[{"red": 0, "green": 1, "blue": 2, "1": "a", "-2": "stuff", "3.1": [1, 2, 3]}, [], [-1, 0, "a string"]]
inputFile = open("saved.json")
object_ = json.load(inputFile)
object_