Strings and Files
Python programs often need to work with text saved in files. We’ll read text into Python, edit it as a string, and save the result. We’ll also see why the same file can look different when two programs open it.
Text Files
A file keeps data after a program finishes. Reading input from a file also lets us run the same program on new text without editing the program.
The open function returns a file object, which lets our program read or write the file. Its read method returns the contents as one string, including spaces and line breaks. A with block keeps the file open for the indented code and closes it when the block ends. The string we read remains available afterward.
We will turn a short poem into a webpage. Save this example as publish_text.py in a practice folder. It creates poem.txt with two lines of text, then opens the file to read them:
with open('poem.txt', 'w', encoding='utf-8') as f:
f.write('the cat sat\non the warm mat\n')
with open('poem.txt', encoding='utf-8') as f:
contents = f.read()
print(contents, end='')Run python3 publish_text.py from that folder. The program prints the poem. end='' tells print not to add a newline after the one already in contents. encoding='utf-8' tells Python how to interpret the text stored in the file, which we will examine later.
When we read from a file, Python keeps track of where the next read should start. After read() reaches the end, another read() returns an empty string. Opening the file again starts a new read from the beginning.
Use a separate file_checks.py for these short experiments:
with open('poem.txt', 'w', encoding='utf-8') as f:
f.write('the cat sat\non the warm mat\n')
with open('poem.txt', encoding='utf-8') as f:
first = f.read()
second = f.read()
print(repr(second)) # ''
with open('poem.txt', encoding='utf-8') as f:
for line in f:
print(repr(line)) # 'the cat sat\n', then 'on the warm mat\n'
A path describes where a file is located. An absolute path starts from the top of a drive and identifies the same location wherever the program runs. A relative path starts from the program’s working directory, usually the folder where we launched Python. That folder can be different from the folder containing the program. A FileNotFoundError means there is no file at the location the path describes.
If the working directory is /Users/alice/csci40, then poem.txt means /Users/alice/csci40/poem.txt and data/poem.txt means /Users/alice/csci40/data/poem.txt. On Windows, an absolute path might begin C:\Users\alice\csci40.
import os
print(os.getcwd()) # the current working directoryIn a macOS, Linux, or Git Bash terminal, pwd displays that directory, ls lists its files, and cd data moves into a folder called data. In Windows Command Prompt, use cd without an argument to display the directory and dir to list files. cd .. moves up one folder. Return to the folder containing poem.txt before continuing.
String Operations
A string is an ordered sequence of characters. Indexing selects one character, while a slice selects a range. Positions start at zero, and a slice stops before its ending position. Both operations return strings, even when the result is only one character. The in operator checks whether a substring occurs, with uppercase and lowercase treated as different characters.
Put these experiments in string_checks.py, separate from the exporter:
word = 'starlight'
print(word[0]) # s
print(word[1:5]) # tarl
print(word[-3:]) # ght
print('star' in word) # True
print('Star' in word) # Falseword[-3:] starts three positions from the end and keeps the rest of the string.
Strings are immutable: their characters cannot be changed in place. A string method is an operation called through a string, such as text.replace(...). Methods that change text return a new string, so we must keep that return value to use the result. replace(old, new) replaces every occurrence of old. An optional third argument limits the number of replacements.
label = 'banana'
changed = label.replace('a', 'o', 2)
print(changed) # bonona
print(label) # banana
label.replace('b', 'p')
print(label) # bananaThe split method divides a string into a list of pieces. With a separator argument, it splits at each occurrence of that exact separator, including empty pieces between adjacent separators. Without an argument, split() splits on whitespace and skips repeated whitespace. The join method combines a sequence of strings, inserting its separator between neighboring pieces.
parts = 'red,green,,blue'.split(',')
print(parts) # ['red', 'green', '', 'blue']
print('|'.join(parts[-3:])) # green||blue
print('red green\tblue'.split()) # ['red', 'green', 'blue']
print('red green'.split(' ')) # ['red', '', 'green']The find method locates the first occurrence of a substring. It returns that occurrence’s position, or -1 if the substring is absent. Its optional second argument says where to begin searching, but the returned position is still measured from the start of the whole string.
line = 'Use `ls` then `pwd`.'
print(line.find('`')) # 4
print(line.find('`', 5)) # 7
print(line.find('!')) # -1Text Transformations
A text transformation takes a string and constructs another string from it. We can combine several operations by passing each result to the next operation. Their order matters when an earlier step introduces characters that a later step also recognizes.
HTML uses <, >, and & to express markup. To display those characters as ordinary text, we escape them by replacing them with character references such as <. Escaping preserves the document’s text while preventing the browser from interpreting it as HTML.
Try this conversion with the poem stored directly in a string:
contents = 'the cat sat\non the warm mat\n'
safe_text = contents.replace('&', '&')
safe_text = safe_text.replace('<', '<').replace('>', '>')
page = '<!DOCTYPE html><html><head><meta charset="utf-8">'
page = page + '<title>Poem</title></head>'
page = page + '<body><pre>' + safe_text + '</pre></body></html>'
print(page)The <pre> element preserves the poem’s spaces and line breaks. Replacing & first avoids changing the ampersands introduced by < and >.
Writing saves a program’s results for another program or a person to use later. The mode argument to open specifies the operation: 'r' reads a file and 'w' writes one. Reading is the default mode. Opening with 'w' creates the file if necessary and erases any existing contents. The write method writes its string exactly, without adding a newline, and returns the number of characters written.
Try this in file_checks.py:
with open('shopping.txt', 'w', encoding='utf-8') as f:
print(f.write('fries\n')) # 6
print(f.write('salsa\n')) # 6
with open('shopping.txt', encoding='utf-8') as f:
print(repr(f.read())) # 'fries\nsalsa\n'This complete example saves a small HTML page as poem.html:
page = '<!DOCTYPE html><html><head><meta charset="utf-8">'
page += '<title>Poem</title></head><body><pre>'
page += 'the cat sat\non the warm mat</pre></body></html>'
with open('poem.html', 'w', encoding='utf-8') as f:
f.write(page)
print('wrote poem.html')Run python3 publish_text.py and open poem.html in a browser. Try adding café & <tea> to the poem, rerun the script, and reload the page. The page should display those characters literally. The completed exporter and sample poem are available to compare with your files.
Character Codes
A computer stores numbers, so software needs an agreed way to represent characters with numbers. A character set assigns a number, called a code point, to each character it includes. ASCII assigns code points from 0 through 127 to English letters, digits, punctuation, and control characters such as newline. Unicode extends this idea to characters used across languages. ASCII’s characters retain the same code points in Unicode.
The ord function returns a character’s code point, and chr returns the character with a given code point. A hexadecimal number writes that same value using digits 0 through 9 and letters A through F. Use the chart for lookups during practice and open-note quizzes. You do not need to memorize character codes or convert number bases by hand.
The table below shows ASCII characters with their decimal and hexadecimal codes. (All the cheatsheets from this reading are available as a PDF here.)
| Decimal | Hex | Character | Decimal | Hex | Character | Decimal | Hex | Character | Decimal | Hex | Character |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 32 | 20 | space | 56 | 38 | 8 |
80 | 50 | P |
104 | 68 | h |
| 33 | 21 | ! |
57 | 39 | 9 |
81 | 51 | Q |
105 | 69 | i |
| 34 | 22 | " |
58 | 3A | : |
82 | 52 | R |
106 | 6A | j |
| 35 | 23 | # |
59 | 3B | ; |
83 | 53 | S |
107 | 6B | k |
| 36 | 24 | $ |
60 | 3C | < |
84 | 54 | T |
108 | 6C | l |
| 37 | 25 | % |
61 | 3D | = |
85 | 55 | U |
109 | 6D | m |
| 38 | 26 | & |
62 | 3E | > |
86 | 56 | V |
110 | 6E | n |
| 39 | 27 | ' |
63 | 3F | ? |
87 | 57 | W |
111 | 6F | o |
| 40 | 28 | ( |
64 | 40 | @ |
88 | 58 | X |
112 | 70 | p |
| 41 | 29 | ) |
65 | 41 | A |
89 | 59 | Y |
113 | 71 | q |
| 42 | 2A | * |
66 | 42 | B |
90 | 5A | Z |
114 | 72 | r |
| 43 | 2B | + |
67 | 43 | C |
91 | 5B | [ |
115 | 73 | s |
| 44 | 2C | , |
68 | 44 | D |
92 | 5C | \ |
116 | 74 | t |
| 45 | 2D | - |
69 | 45 | E |
93 | 5D | ] |
117 | 75 | u |
| 46 | 2E | . |
70 | 46 | F |
94 | 5E | ^ |
118 | 76 | v |
| 47 | 2F | / |
71 | 47 | G |
95 | 5F | _ |
119 | 77 | w |
| 48 | 30 | 0 |
72 | 48 | H |
96 | 60 | ` |
120 | 78 | x |
| 49 | 31 | 1 |
73 | 49 | I |
97 | 61 | a |
121 | 79 | y |
| 50 | 32 | 2 |
74 | 4A | J |
98 | 62 | b |
122 | 7A | z |
| 51 | 33 | 3 |
75 | 4B | K |
99 | 63 | c |
123 | 7B | { |
| 52 | 34 | 4 |
76 | 4C | L |
100 | 64 | d |
124 | 7C | | |
| 53 | 35 | 5 |
77 | 4D | M |
101 | 65 | e |
125 | 7D | } |
| 54 | 36 | 6 |
78 | 4E | N |
102 | 66 | f |
126 | 7E | ~ |
| 55 | 37 | 7 |
79 | 4F | O |
103 | 67 | g |
127 | 7F | DEL |
An escape sequence writes a character that would be awkward to type directly into a string. The backslash and following characters together specify one character in the resulting string. The table below shows common escape sequences and the characters they represent.
| Escape | Meaning | Decimal | Hex | Escape | Meaning | Decimal | Hex |
|---|---|---|---|---|---|---|---|
\n |
newline | 10 | 0A | \\ |
backslash | 92 | 5C |
\t |
tab | 9 | 09 | \' |
single quote | 39 | 27 |
\r |
carriage return | 13 | 0D | \" |
double quote | 34 | 22 |
The escape \x takes two hexadecimal digits, \u takes four, and \U takes eight. Uppercase and lowercase hexadecimal digits have the same value.
print(ord('H')) # 72
print(chr(72)) # H
print('\x48\x69') # Hi
print(chr(ord('b') - 32)) # B
print(len('cat\n')) # 4
print(repr('cat\n')) # 'cat\n'The chart shows that the ASCII lowercase letters are 32 above their uppercase partners. Subtracting 32 works for those letters, but is not a general uppercase operation for every Unicode character.
What looks like one character on screen can consist of several code points. For strings, len counts code points and equality compares their sequence. Normalization puts equivalent sequences into a common form so they can be compared consistently. The NFC form combines a letter and its accent where a precomposed character is available.
import unicodedata
print(len('á')) # 1
print(len('a\u0301')) # 2
print('á' == 'a\u0301') # False
print(unicodedata.normalize('NFC', 'a\u0301') == 'á') # TrueEncodings
A file stores bytes, each with a value from 0 to 255. An encoding is a set of rules for representing text with those bytes. Writing text involves encoding a string into bytes. Reading it involves decoding the bytes using the same rules. Some characters take more than one byte.
UTF-8 uses one byte for each ASCII character and more than one byte for other characters. An ASCII file can therefore be read as UTF-8 without changing its text. The length of a string and the length of its encoded bytes need not be the same.
text = 'café'
data = text.encode('utf-8')
print(data) # b'caf\xc3\xa9'
print(len(text)) # 4
print(len(data)) # 5
print(data.decode('utf-8')) # caféThe leading b identifies a bytes value. In a bytes literal, \x gives a byte’s value, not a complete Unicode character.
Bytes are also a sequence. Indexing a bytes value returns an integer, while slicing it returns another bytes value. This lets us inspect the stored data before interpreting it as text.
data = b'Hi'
print(data[0]) # 72
print(data[:1]) # b'H'
print(data[:1].decode('ascii')) # H
In text mode, a file object performs the conversion for us: reading decodes bytes and writing encodes strings. Binary mode, written 'rb' for reading or 'wb' for writing, works directly with bytes instead. It is useful when we want to keep the stored data separate from the choice of encoding.
Read the same poem as bytes and decode it explicitly:
with open('poem.txt', 'w', encoding='utf-8') as f:
f.write('the cat sat\non the warm mat\n')
with open('poem.txt', 'rb') as f:
data = f.read()
contents = data.decode('utf-8')
print(contents, end='')This produces the same text as the earlier open('poem.txt', encoding='utf-8') example.
Using the wrong encoding can raise UnicodeDecodeError because the bytes do not represent valid text in that encoding. Other byte sequences are valid under several encodings but produce different text. A successful decode therefore tells us the bytes were accepted, not that we chose the intended interpretation.
data = 'é'.encode('utf-8')
print(data.decode('utf-8')) # é
print(data.decode('ascii')) # UnicodeDecodeErrorASCII cannot decode either of the two bytes UTF-8 uses for é. For a file supplied in another encoding, pass that encoding’s name to decode or open.
Processing Text
Text formats often use markers to give part of a document a special meaning. A program can locate the markers, select the text between them, and rebuild the surrounding text. This requires keeping track of positions in the original string even while constructing a different result.
A missing marker also needs a decision. Because find returns -1, using its result as an ordinary slice endpoint can silently select the wrong text. Check whether a marker was found before using its position.
A poem editor might put a note in brackets. This function removes the first complete note and leaves unmatched brackets unchanged:
def remove_note(text):
start = text.find('[')
if start == -1:
return text
end = text.find(']', start + 1)
if end == -1:
return text
return text[:start] + text[end + 1:]
print(remove_note('the [quiet] cat')) # the cat
print(remove_note('the [quiet cat')) # the [quiet catFor a marker containing several characters, move past it by its full length. Here start + 2 skips both characters in {{:
line = 'Read {{slowly}} today'
start = line.find('{{')
end = line.find('}}', start + 2)
print(line[start + 2:end]) # slowlyTo process several marked sections, a loop can track its current position and build a result string. After handling one section, it advances past the closing marker and continues through the remaining text. Every branch must either advance that position or end the loop. Whether the program preserves an unmatched marker, skips it, or stops there is part of the format’s behavior.
This version removes every complete bracketed note:
def remove_notes(text):
result = ''
i = 0
while i < len(text):
if text[i] == '[':
end = text.find(']', i + 1)
if end != -1:
i = end + 1
else:
result += text[i:]
break
else:
result += text[i]
i += 1
return result
print(repr(remove_notes('the [quiet] cat [sleeps]'))) # 'the cat '
print(remove_notes('the cat [sleeps')) # the cat [sleeps
The text exporter uses the same separation of tasks: read the source text, build the transformed string, and write the result. Specifying UTF-8 when reading and writing keeps the conversion consistent. The HTML declaration <meta charset="utf-8"> tells the browser how to decode the saved page.