Here are some exercises for you to try on your own.
Write a program that makes a backup of a file. Your program should prompt the user for the name of the file to copy and then create a new file with the same contents but with the bak file extension.
Suppose the file alkaline_metals.txt contains the name, atomic number, and atomic weight of the alkaline earth metals:
| | beryllium 4 9.012 |
| | magnesium 12 24.305 |
| | calcium 20 20.078 |
| | strontium 38 87.62 |
| | barium 56 137.327 |
| | radium 88 226 |
Write a for loop to read the contents of alkaline_metals.txt and store it in a list of lists, with each inner list containing the name, atomic number, and atomic weight for an element. (Hint: Use str.split.)
All of the file-reading functions you have seen in this chapter read forward through the file from the first character or line to the last. How could you write a function that would read backward through a file?
In , you used the “For Line in File” technique to process data line by line, breaking it into pieces using the string method str.split. Rewrite the function process_file to skip the header as usual, but then use the Read technique to read all the data at once.
Modify the file reader in read_smallest_skip.py of , so that it can handle files with no data after the header.
Modify the file reader in read_smallest_skip.py of , so that it uses a continue statement inside the loop instead of an if statement. Which form do you find easier to read?
Modify the PDB file reader of , so that it ignores blank lines and comment lines in PDB files. A blank line contains only space and tab characters (that is, one that looks empty when viewed). A comment is any line beginning with the keyword CMNT.
Modify the PDB file reader to check that the serial numbers on atoms start at 1 and increase by 1. What should the modified function do if it finds a file that doesn’t obey this rule?
Footnotes