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