055. 编写一个函数,实现简单的文本文件的行数统计

以下是一个简单的Python函数,用于统计文本文件的行数。这个函数会打开指定的文本文件,并逐行读取以计算总行数。

示例代码

def count_lines(file_path):
    """
    统计文本文件的行数
    :param file_path: 文本文件的路径
    :return: 文件的行数
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()  # 读取所有行
            return len(lines)  # 返回行数
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到!")
        return -1
    except Exception as e:
        print(f"发生错误:{e}")
        return -1

# 示例用法
if __name__ == "__main__":
    file_path = "example.txt"  # 替换为你的文件路径
    line_count = count_lines(file_path)
    if line_count >= 0:
        print(f"文件 {file_path} 的行数为:{line_count}")

代码说明:

open(file_path, 'r', encoding='utf-8')

  • 打开指定路径的文件,以只读模式('r')打开。

  • 使用utf-8编码读取文件,以支持多种字符集(如中文等)。

file.readlines():读取文件的所有行,并将每一行作为一个元素存储在列表中。

len(lines):计算列表的长度,即文件的总行数。

异常处理

  • 使用try-except块捕获可能的错误,例如文件不存在(FileNotFoundError)或其他异常。

  • 如果发生错误,打印错误信息并返回-1作为错误标志。

示例运行

假设有一个名为example.txt的文件,内容如下:

第一行
第二行
第三行

运行代码后,输出将为:

文件 example.txt 的行数为:3

注意事项

文件编码:如果文件的编码不是utf-8,可能会导致读取错误。如果文件使用其他编码(如gbk),可以在open函数中指定正确的编码,例如:

with open(file_path, 'r', encoding='gbk') as file:

大文件处理:如果文件非常大,一次性读取所有行可能会占用大量内存。可以使用逐行读取的方式优化:

def count_lines(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            line_count = 0
            for line in file:
                line_count += 1
            return line_count
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到!")
        return -1
    except Exception as e:
        print(f"发生错误:{e}")
        return -1

这种方式逐行读取文件,不会占用太多内存,适合处理大文件。

扩展功能

如果你需要统计文件中的空行数或非空行数,可以进一步扩展这个函数。例如:

def count_lines(file_path, count_empty=False):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            total_lines = 0
            empty_lines = 0
            for line in file:
                total_lines += 1
                if line.strip() == "":
                    empty_lines += 1
            if count_empty:
                return total_lines, empty_lines
            else:
                return total_lines
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到!")
        return -1
    except Exception as e:
        print(f"发生错误:{e}")
        return -1

# 示例用法
total_lines, empty_lines = count_lines("example.txt", count_empty=True)
print(f"总行数:{total_lines}")
print(f"空行数:{empty_lines}")

视频讲解

BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)