赞
踩
使用len(file.readlines())
:
file_path = 'your_file.txt'
with open(file_path, 'r') as file:
line_count = len(file.readlines())
print("方法1 - 文本文件的行数:", line_count)
使用sum(1 for line in file)
:
file_path = 'your_file.txt'
with open(file_path, 'r') as file:
line_count = sum(1 for line in file)
print("方法2 - 文本文件的行数:", line_count)
逐行迭代计数:
file_path = 'your_file.txt'
line_count = 0
with open(file_path, 'r') as file:
for line in file:
line_count += 1
print("方法3 - 文本文件的行数:", line_count)
使用wc
命令(仅限Unix/Linux系统):
import subprocess
file_path = 'your_file.txt'
line_count = int(subprocess.check_output(["wc", "-l", file_path]).split()[0])
print("方法4 - 文本文件的行数:", line_count)
使用pandas
库:
import pandas as pd
file_path = 'your_file.txt'
df = pd.read_csv(file_path, header=None)
line_count = len(df)
print("方法5 - 文本文件的行数:", line_count)
pandas
库,适用于处理数据的场景。Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。