python - 使用 python 检索行数

标签 python

我正在尝试在 ubuntu 上使用 python 检索文件的行数。

我尝试了以下方法:

os.system("wc -l fileName")

但它返回类似

numberOfLines fileName
0

当我尝试检索结果时: l = os.system("wc -l 文件名")

我得到l = 0

我还尝试拆分结果以仅保留第一个元素,但这会引发 AttributeError: 'int' object has no attribute 'split'

如何获得我要查找的行数?

最佳答案

os.system 将返回 wc -l 命令的退出值,如果没有错误发生,该值为零。

您想要程序的实际输出:

#TODO: handle CalledProcessError, malformatted output where appropriate

wc_output = subprocess.check_output(["wc", "-l", fileName])
num_lines = int(wc_output.split()[0])

关于python - 使用 python 检索行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22252807/

相关文章:

python - 我可以像分类一样进行线性回归预测吗?

javascript - 通过CSV文件解析转换为JSON格式文件

python - 如何删除我在他人计算机上设置的 cookie?

python - SQLAlchemy 子查询获取 AttributeError : 'Query' object has no attribute 'is_clause_element'

python - 如何在 Python 中将用户输入的二进制值转换为 ASCII 字符?

python - wxpython 防止Ctrl+Enter改变焦点

python - 使用 BeautifulSoup 在 HTML 中搜索和替换

python - 在 Python 中使用正则表达式提取多个匹配项

Python遍历数组,同时找到前k个元素的平均值

python - 反斜杠后跟 python 字符串中的数字