gpt4 book ai didi

python - 使用 python 检索行数

转载 作者:行者123 更新时间:2023-11-30 23:27:11 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com