Text
stringlengths
1
9.41k
Return-Path: <p.. Date: Sat, 5 Jan .. To: source@coll.. From: stephen... Subject: [sakai]... Details: http:/...
…| |---|---| From stephen.m.. Return-Path: <p.. Date: Sat, 5 Jan .. To: source@coll.. From: stephen... Subject: [sakai]... Details: http:/... … Figure 7.2: A File Handle If the file does not exist, open will fail with a traceback and you will not get a handle to access the contents of the file: >>> fhand = open(...
For example, this is a sample of a text file which records mail activity from various individuals in an open source project development team: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: <postmaster@collab.sakaiproject.org> Date: Sat, 5 Jan 2008 09:12:18 -0500 To: source@collab.sakaiproject.org...
For more information about the mbox format, see en.wikipedia.org/wiki/Mbox. To break the file into lines, there is a special character that represents the “end of the line” called the newline character. In Python, we represent the newline character as a backslash-n in string constants. Even though this looks like two...
When we look at the variable by entering “stuff” in the interpreter, it shows us the \n in the string, but when we use print to show the string, we see the string broken into two lines by the newline character. >>> stuff = 'Hello\nWorld!' >>> stuff 'Hello\nWorld!' >>> print(stuff) Hello World! >>> stuff = 'X\nY' >>> p...
Our for loop simply counts the number of lines in the file and prints them out.
The rough translation of the for loop into English is, “for each line in the file represented by the file handle, add one to the count variable.” The reason that the open function does not read the entire file is that the file might be quite large with many gigabytes of data.
The open statement takes the same amount of time regardless of the size of the file.
The for loop actually causes the data to be read from the file. When the file is read using a for loop in this manner, Python takes care of splitting the data in the file into separate lines using the newline character.
Python reads each line through the newline and includes the newline as the last character in the line variable for each iteration of the for loop. Because the for loop reads the data one line at a time, it can efficiently read and count the lines in very large files without running out of main memory to store the data...
The above program can count the lines in any size file using very little memory since each line is read, counted, and then discarded. If you know the file is relatively small compared to the size of your main memory, you can read the whole file into one string using the read method on the file handle. >>> fhand = ope...
We use string slicing to print out the first 20 characters of the string data stored in inp. When the file is read in this manner, all the characters including all of the lines and newline characters are one big string in the variable inp.
Remember that this ----- form of the open function should only be used if the file data will fit comfortably in the main memory of your computer. If the file is too large to fit in main memory, you should write your program to read the file in chunks using a for or while loop. ##### 7.5 Searching through a file W...
We can combine the pattern for reading a file with string methods to build simple search mechanisms. For example, if we wanted to read a file and only print out lines which started with the prefix “From:”, we could use the string method startswith to select only those lines with the desired prefix: fhand = open('mbox...
This is due to that invisible _newline character.
Each of the lines ends with a newline, so the print statement_ prints the string in the variable line which includes a newline and then print adds _another newline, resulting in the double spacing effect we see._ We could use line slicing to print all but the last character, but a simpler approach is to use the rstrip...
The basic idea of the search loop is that you are looking for “interesting” lines and effectively skipping “uninteresting” lines.
And then when we find an interesting line, we do something with that line. We can structure the loop to follow the pattern of skipping uninteresting lines as follows: fhand = open('mbox-short.txt') **for line in fhand:** line = line.rstrip() _# Skip 'uninteresting lines'_ **if not line.startswith('From:'):** **conti...
In English, the uninteresting lines are those which do not start with “From:”, which we skip using continue.
For the “interesting” lines (i.e., those that start with “From:”) we perform the processing on those lines. We can use the find string method to simulate a text editor search that finds lines where the search string is anywhere in the line.
Since find looks for an occurrence of a string within another string and either returns the position of the string or -1 if the string was not found, we can write the following loop to show lines which contain the string “@uct.ac.za” (i.e., they come from the University of Cape Town in South Africa): fhand = open('mbo...
It would be more usable to ask the user to enter the file name string each time the program runs so they can use our program on different files without changing the Python code. This is quite simple to do by reading the file name from the user using raw_input as follows: fname = input('Enter the file name: ') fhand =...
Now we can run the program repeatedly on different files. python search6.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python search6.py Enter the file name: mbox-short.txt There were 27 subject lines in mbox-short.txt Before peeking at the next section, take a look at the above program ...
This is your last chance. What if our user types something that is not a file name? python search6.py Enter the file name: missing.txt Traceback (most recent call last): File "search6.py", line 2, in <module> fhand = open(fname) FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt' python search6.py ...
Users will eventually do every possible thing they can do to break your programs, either on purpose or with malicious intent.
As a matter of fact, an important part of any software development team is a person or group called _Quality Assurance (or QA for short) whose very job it is to do the craziest things_ possible in an attempt to break the software that the programmer has created. The QA team is responsible for finding the flaws in prog...
So the QA team is the programmer’s best friend. So now that we see the flaw in the program, we can elegantly fix it using the try/except structure.
We need to assume that the open call might fail and add recovery code when the open fails as follows: fname = input('Enter the file name: ') **try:** fhand = open(fname) **except:** print('File cannot be opened:', fname) exit() count = 0 **for line in fhand:** **if line.startswith('Subject:'):** count = count + 1 ...
It is a function that we call that never returns.
Now when our user (or QA team) types in silliness or bad file names, we “catch” them and recover gracefully: ----- python search7.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python search7.py Enter the file name: na na boo boo File cannot be opened: na na boo boo Protecting the open ...
We use the term “Pythonic” when we are doing something the “Python way”.
We might say that the above example is the Pythonic way to open a file. Once you become more skilled in Python, you can engage in repartee with other Python programmers to decide which of two equivalent solutions to a problem is “more Pythonic”.
The goal to be “more Pythonic” captures the notion that programming is part engineering and part art.
We are not always interested in just making something work, we also want our solution to be elegant and to be appreciated as elegant by our peers. ##### 7.8 Writing files To write a file, you have to open it with mode “w” as a second parameter: >>> fout = open('output.txt', 'w') >>> print(fout) <_io.TextIOWrapper na...
If the file doesn’t exist, a new one is created. The write method of the file handle object puts data into the file, returning the number of characters written.
The default write mode is text for writing (and reading) strings. >>> line1 = "This here's the wattle,\n" >>> fout.write(line1) 24 Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end. We must make sure to manage the ends of lines as we write to the file by e...
The print statement automatically appends a newline, but the write method does not add the newline automatically. >>> line2 = 'the emblem of our land.\n' >>> fout.write(line2) 24 ----- When you are done writing, you have to close the file to make sure that the last bit of data is physically written to the disk so i...
When we are writing files, we want to explicitly close the files so as to leave nothing to chance. ##### 7.9 Debugging When you are reading and writing files, you might run into problems with whitespace.
These errors can be hard to debug because spaces, tabs, and newlines are normally invisible: >>> s = '1 2\t 3\n 4' >>> print(s) 1 2 3 4 The built-in function repr can help.
It takes any object as an argument and returns a string representation of the object.
For strings, it represents whitespace characters with backslash sequences: >>> print(repr(s)) '1 2\t 3\n 4' This can be helpful for debugging. One other problem you might run into is that different systems use different characters to indicate the end of a line.
Some systems use a newline, represented \n. Others use a return character, represented \r. Some use both.
If you move files between different systems, these inconsistencies might cause problems. For most systems, there are applications to convert from one format to another. You can find them (and read more about this issue) at wikipedia.org/wiki/Newline. Or, of course, you could write one yourself. ##### 7.10 Glossary *...
“Using try and except is** the Pythonic way to recover from missing files”. **Quality Assurance A person or team focused on insuring the overall quality of** a software product.
QA is often involved in testing a product and identifying problems before the product is released. **text file A sequence of characters stored in permanent storage like a hard drive.** ##### 7.11 Exercises Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upp...
Executing the program will look as follows: python shout.py Enter a file name: mbox-short.txt FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008 RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.ORG> RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90]) BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA; SAT, 0...
Count these lines and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence. Enter the file name: mbox.txt Average spam confidence: 0.894128046745 Enter the file name: mbox-short.txt Average spam confidence: 0.750718518519 Test your file on the mbox.txt and mbox-short.txt files. Exercise 3: Sometimes when programmers...
The program should behave normally for all other files which exist and don’t exist.
Here is a sample execution of the program: ----- python egg.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python egg.py Enter the file name: missing.tyxt File cannot be opened: missing.tyxt python egg.py Enter the file name: na na boo boo NA NA BOO BOO TO YOU - You have been punk'd! W...
In a string, the values are characters; in a list, they can be any type.
The values in list are called elements or sometimes _items._ There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]): ~~ {.python} [10, 20, 30, 40][‘crunchy frog’, ‘ram bladder’, ‘lark vomit’] ~~ {.python} The first example is a list of four integers.
The second is a list of three strings. The elements of a list don’t have to be the same type.
The following list contains a string, a float, an integer, and (lo!) another list: ['spam', 2.0, 5, [10, 20]] A list within another list is nested. A list that contains no elements is called an empty list; you can create one with empty brackets, []. As you might expect, you can assign list values to variables: >>>...
The expression inside the brackets specifies the index.
Remember that the indices start at 0: >>> print(cheeses[0]) Cheddar Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list.
When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. >>> numbers = [17, 123] >>> numbers[1] = 5 >>> print(numbers) [17, 5] The one-eth element of numbers, which used to be 123, is now 5. You can think of a list as a relationship between in...
This relationship is called a mapping; each index “maps to” one of the elements. List indices work the same way as string indices: - Any integer expression can be used as an index. - If you try to read or write an element that does not exist, you get an IndexError. - If an index has a negative value, it count...
The syntax is the same as for strings: **for cheese in cheeses:** print(cheese) ----- This works well if you only need to read the elements of the list.
But if you want to write or update the elements, you need the indices.
A common way to do that is to combine the functions range and len: **for i in range(len(numbers)):** numbers[i] = numbers[i] * 2 This loop traverses the list and updates each element.
len returns the number of elements in the list. range returns a list of indices from 0 to n − 1, where n is the length of the list. Each time through the loop, i gets the index of the next element.
The assignment statement in the body uses i to read the old value of the element and to assign the new value. A for loop over an empty list never executes the body: **for x in empty:** print('This never happens.') Although a list can contain another list, the nested list still counts as a single element.
The length of this list is four: ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] ##### 8.4 List operations The + operator concatenates lists: >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print(c) [1, 2, 3, 4, 5, 6] Similarly, the operator repeats a list a given number of times: >>> [0] * 4 ...
The second example repeats the list three times. ----- ##### 8.5 List slices The slice operator also works on lists: >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f'] If you omit the first index, the slice starts at the beginning.
If you omit the second, the slice goes to the end.
So if you omit both, the slice is a copy of the whole list. >>> t[:] ['a', 'b', 'c', 'd', 'e', 'f'] Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate lists. A slice operator on the left side of an assignment can update multiple elements: >>> t =...
For example, append adds a new element to the end of a list: >>> t = ['a', 'b', 'c'] >>> t.append('d') >>> print(t) ['a', 'b', 'c', 'd'] extend takes a list as an argument and appends all of the elements: >>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> print(t1) ['a', 'b', 'c', 'd', 'e'] This e...
If you accidentally write t = t.sort(), you will be disappointed with the result. ##### 8.7 Deleting elements There are several ways to delete elements from a list.
If you know the index of the element you want, you can use pop: >>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> print(t) ['a', 'c'] >>> print(x) b pop modifies the list and returns the element that was removed.
If you don’t provide an index, it deletes and returns the last element. If you don’t need the removed value, you can use the del operator: >>> t = ['a', 'b', 'c'] >>> del t[1] >>> print(t) ['a', 'c'] If you know the element you want to remove (but not the index), you can use remove: >>> t = ['a', 'b', 'c'] >>> t.r...
The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable. We could rewrite an earlier program that computed the average of a list of numbers entered by the user using a list. First, the program to compute an average without a list: total = 0 count = 0 **while (True):...
At the end of the program, we simply compute the sum of the numbers in the list and divide it by the count of the numbers in the list to come up with the average. ##### 8.9 Lists and strings A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string.
To convert from a string to a list of characters, you can use list: >>> s = 'spam' >>> t = list(s) >>> print(t) ['s', 'p', 'a', 'm'] Because list is the name of a built-in function, you should avoid using it as a variable name.
I also avoid the letter l because it looks too much like the number 1. So that’s why I use t. The list function breaks a string into individual letters.
If you want to break a string into words, you can use the split method: >>> s = 'pining for the fjords' >>> t = s.split() >>> print(t) ['pining', 'for', 'the', 'fjords'] >>> print(t[2]) the Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a...
The following example uses a hyphen as a delimiter: >>> s = 'spam-spam-spam' >>> delimiter = '-' >>> s.split(delimiter) ['spam', 'spam', 'spam'] ----- join is the inverse of split.
It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter: >>> t = ['pining', 'for', 'the', 'fjords'] >>> delimiter = ' ' >>> delimiter.join(t) _'pining for the fjords'_ In this case the delimiter is a space character,...
Often we want to find the “interesting lines” and then _parse the line to find some interesting part of the line.
What if we wanted to print_ out the day of the week from those lines that start with “From”? From stephen.marquard@uct.ac.zaSat Jan 5 09:14:16 2008 The split method is very effective when faced with this kind of problem.
We can write a small program that looks for lines where the line starts with “From”, split those lines, and then print out the third word in the line: fhand = open('mbox-short.txt') **for line in fhand:** line = line.rstrip() **if not line.startswith('From '): continue** words = line.split() print(words[2]) _# Code: ...
This contracted form of the if functions the same as if the continue were on the next line and indented. The program produces the following output: Sat Fri Fri Fri ... Later, we will learn increasingly sophisticated techniques for picking the lines to work on and how we pull those lines apart to find the exact bit o...
There are two possible states: a ‘banana’ a ‘banana’ b ‘banana’ b Figure 8.1: Variables and Objects In one case, a and b refer to two different objects that have the same value.
In the second case, they refer to the same object. To check whether two variables refer to the same object, you can use the is operator. >>> a = 'banana' >>> b = 'banana' >>> a is b True In this example, Python only created one string object, and both a and b refer to it. But when you create two lists, you get two ...
If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value.
If you execute a = [1,2,3], a refers to a list object whose value is a particular sequence of elements.
If another list has the same elements, we would say it has the same value. ----- ##### 8.12 Aliasing If a refers to an object and you assign b = a, then both variables refer to the same object: >>> a = [1, 2, 3] >>> b = a >>> b is a True The association of a variable with an object is called a reference.
In this example, there are two references to the same object. An object with more than one reference has more than one name, so we say that the object is aliased. If the aliased object is mutable, changes made with one alias affect the other: >>> b[0] = 17 >>> print(a) [17, 2, 3] Although this behavior can be usef...
In general, it is safer to avoid aliasing when you are working with mutable objects. For immutable objects like strings, aliasing is not as much of a problem.
In this example: a = 'banana' b = 'banana' it almost never makes a difference whether a and b refer to the same string or not. ##### 8.13 List arguments When you pass a list to a function, the function gets a reference to the list.
If the function modifies a list parameter, the caller sees the change.
For example, delete_head removes the first element from a list: **def delete_head(t):** **del t[0]** Here’s how it is used: >>> letters = ['a', 'b', 'c'] >>> delete_head(letters) >>> print(letters) ['b', 'c'] ----- The parameter t and the variable letters are aliases for the same object. It is important to dis...
For example, the append method modifies a list, but the + operator creates a new list: >>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print(t1) [1, 2, 3] >>> print(t2) None >>> t3 = t1 + [3] >>> print(t3) [1, 2, 3] >>> t2 is t3 False This difference is important when you write functions that are supposed to modify list...
For example, this function does not delete the head of a list: **def bad_delete_head(t):** t = t[1:] _# WRONG!_ The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument. An alternative is to write a function that creates ...
For example, tail returns all but the first element of a list: **def tail(t):** **return t[1:]** This function leaves the original list unmodified.
Here’s how it is used: >>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> print(rest) ['b', 'c'] Exercise 1: Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. Then write a function called middle that takes a list and returns a new list t...
Don’t forget that most list methods modify the argument and return None. This is the opposite of the string methods, which return a new string and leave the original alone. If you are used to writing string code like this: word = word.strip() It is tempting to write list code like this: ~~ {.python} t = t.sort() # W...
~~ Because sort returns None, the next operation you perform with t is likely to fail. Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode.
The methods and operators that lists share with other sequences (like strings) are documented [at https://docs.python.org/2/library/stdtypes.html#string-methods.](https://docs.python.org/2/library/stdtypes.html#string-methods) The methods and operators that only apply to mutable sequences are documented [at https://doc...
Pick an idiom and stick with it. Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use pop, remove, del, or even a slice assignment. To add an element, you can use the append method or the + operator.