128k views
2 votes
The following code segment is supposed to read all of the lines from test.txt and save them in copy.txt. infile = open("test.txt", "r") outfile = open("copy.txt", "w") line = infile.readline() ____________________ outfile.write(line) line = infile.readline() infile.close() outfile.close() Which line of code should be placed in the blank to achieve this goal?

User Kevin Cui
by
6.5k points

1 Answer

0 votes

Answer:

The line of code that should be placed is

while line:

The entire code should be as follows:

  1. infile = open("test.txt", "r")
  2. outfile = open("copy.txt", "w")
  3. line = infile.readline()
  4. while line:
  5. outfile.write(line)
  6. line = infile.readline()
  7. infile.close()
  8. outfile.close()

Step-by-step explanation:

The Python built-in function readline() will read one line of text from test.txt per time. Hence, the code in Line 3 will only read the first line of text from test.txt.

To enable our program to read all the lines and copy to copy.txt, we can create a while loop (Line 5) to repeatedly copy the current read line to copy.txt and proceed to read the next line of text from test.txt (Line 6 -7).

"while line" in Line 5 means while the current line is not empty which denotes a condition of True, the codes in Line 6-7 will just keep running to read and copy the text until it reaches the end of file.

User DangerDave
by
6.1k points