with open("file.txt", "r") as f: line_count = len(f.readlines()) print(line_count)
时间: 2024-01-04 20:01:50 浏览: 104
How to count the number of lines in a text file
This code snippet reads the file "file.txt" and counts the number of lines in it. It does this by opening the file in read mode ("r") using a "with" statement, which automatically closes the file when the block of code is finished executing.
The "readlines()" method reads all the lines in the file and returns a list of strings, with each string representing a line in the file. The "len()" function is then used to count the number of lines in the list.
Finally, the line count is printed to the console.
阅读全文