How can Python calculate and output the number of lines and columns in a file?

To count and output the number of lines and columns in a file, you can use the following code:

def count_lines_columns(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
        line_count = len(lines)
        column_count = len(lines[0].split())
        print("行数:", line_count)
        print("列数:", column_count)

count_lines_columns("文件路径")  # 替换为实际的文件路径

The count_lines_columns function here takes a file name as a parameter, then uses the open function to open the file in read-only mode (‘r’). By using the file.readlines() method, all lines can be read at once and stored in a list.

Then, you can obtain the number of lines (i.e. the length of the list) using len(lines), and the number of words in the first line (i.e. the number of columns) using len(lines[0].split()). Here, the split() method is used to split the first line into a list of strings based on spaces, and then the len() function is used to get the length of the list.

Finally, use the print function to display the number of rows and columns.

You need to replace “file path” with your actual file path.

bannerAds