1
2
3
4
5
6
7
8
9
10
11
12
To practice on your own, or to check code you believe shouldn't have been scored as incorrect, go to Trinket.
Post a review on Amazon for the paperback or the Kindle edition.
Email me to give me a compliment, complaint, or correction. I'll respond.
0,1,2,3,4,5,6,7,8,9,10,11
0
0
0
0
The text in info.txt is "boogie". What text does it contain after the following code executes? | with open("info.text", "a") as f: f.write("woogie") |
"boogiewoogie" | ^ *•?boogiewoogie•? *$ |
Rewrite the following two lines to add the text instead of replacing it. | with open("x.txt", "w") as f: f.write("Hi") |
with open("x.txt", "a") as f: f.write("Hi") | ^ *with open\(•x\.txt•, •a•\) as f:\n f\.write\(•Hi•\) *$ |
Open a file, "products.txt", to append. The file handle is prod_file | with open("products.txt", "a") as prod_file: | with `open`(`"products.txt"`, `"`a`"`) `as `prod_file`: | |
Code the next line. The string to append is a new line followed by "Hi". Start by indenting. | with open("greetings.txt", "a") as f: | f.write("\nHi") | f.write("\nHi") |
Assign a string to a variable. Begin the string with a new line. Make up everything else. | new_string = "\nHello, World!" | ^ *[a-zA-Z_][a-zA-Z0-9_]* = •\\n.+• *$ | |
Assign the name of a text file to a variable. Then open the file to append to it. Make everything up. | file_to_open = "students.txt" with open(file_to_open, "a") as f: |
^ *([a-zA-Z_][a-zA-Z0-9_]*) = •[a-zA-Z_][a-zA-Z0-9_]*\.txt•\nwith open\(\1, •a•\) as [a-zA-Z_][a-zA-Z0-9_]*: *$ | |
When the contents of the file greet.txt are displayed, here's what is displayed: Hello. Have a nice day. Write the string to the file. Make up the file handle. |
with open("greet.txt", "w") as f: f.write("Hello.\nHave a nice day.") |
^ *with open\(•greet\.txt•, •w•\) as ([a-zA-Z_][a-zA-Z0-9_]*):\n \1\.write\(•Hello\.\\nHave a nice day\.•\) *$ | |
In two lines, open a text file and display its contents. Use shorthand. Make everything up. | with open("tiny.txt") as f: print(f.read()) |
^ *with open\(•.+\.txt•\) as ([a-zA-Z_][a-zA-Z0-9_]*):\n print\(\1\.read\(\)\) *$ | |
Assign a string to a variable. Then append the string to a text file. Make everything up. | text_to_add = "Hello, World!" with open("hi.txt", "a") as f: f.write(text_to_add) |
^ *([a-zA-Z_][a-zA-Z0-9_]*) = •.+•\nwith open\(•.+\.txt•, •a•\) as ([a-zA-Z_][a-zA-Z0-9_]*):\n \2\.write\(\1\) *$ | |
Write some text to a text file. Then append some more text to that file. Make everything up. | with open("brief_encounter.txt", "w") as f: f.write("Hello.") with open("brief_encounter.txt", "a") as f: f.write("Goodbye") |
^ *with open\(•(.+)\.txt•, •w•\) as ([a-zA-Z_][a-zA-Z0-9_]*):\n \2\.write\(•.+\.•\)\nwith open\(•\1\.txt•, •a•\) as ([a-zA-Z_][a-zA-Z0-9_]*):\n \3\.write\(•.+•\) *$ | |
|
|||