167k views
3 votes
Snpf = open("SNP1.txt", "r")

line = snpf.readline()
while line:
print(line)
line = snpf.readline()
()
Please rewrite this Python code using loop
function to print out all lines.

1 Answer

4 votes

Final answer:

The Python code in question reads and prints contents from a text file. It can be rewritten using a for loop to iterate through each line, and using a context manager to ensure the file is properly closed afterward.

Step-by-step explanation:

The provided Python code opens a text file and prints out each line. To rewrite the code using a loop function, we can use a for loop which iterates over each line in the file directly:

snpf = open("SNP1.txt", "r")\\for line in snpf:\\ print(line)\\snpf.close()

This code uses the with statement, which is a context manager that automatically closes the file after the block of code is executed, preventing file handle leaks. Additionally, using the with statement is considered good practice as it ensures files are properly closed even if an error occurs.

User Aenw
by
8.2k points