使用 python 和 wc -l 计算文件中的行数

win*_*boy 3 python linux cmd

我在 linux 上有这个命令,但type 在 Windows 上转换成问题:

row = run('cat '+'C:/Users/Kyle/Documents/final/VocabCorpus.txt'+" | wc -l").split()[0]
Run Code Online (Sandbox Code Playgroud)

对于语句“wc - l”用于行计数以查看存在多少行。如果我要使用“type”命令将其更改为以下内容,它应该是什么?

我试过这个,但它不起作用。

 row = run('type '+'C:/Users/Kyle/Documents/final/VocabCorpus.txt'+" | wc -l").split()[0]
Run Code Online (Sandbox Code Playgroud)

运行命令如下:

def run(command):
    output = subprocess.check_output(command, shell=True)
    return output
Run Code Online (Sandbox Code Playgroud)

请帮我。谢谢你。

cri*_*007 5

您正在尝试计算文件中的行数?为什么你不能在纯 python 中做到这一点?

像这样的东西?

with open('C:/Users/Kyle/Documents/final/VocabCorpus.txt') as f:
    row = len(f.readlines())
Run Code Online (Sandbox Code Playgroud)

  • 一个稍微好一点的版本是 ``sum(1 for line in f)``,它消耗更少的内存:``f.readlines()`` 读取整个文件,同时迭代 ``f`` 只产生一行时间。 (4认同)