【问题标题】:Using python under linux to count lines in all the files in a folder via terminal在linux下使用python通过终端统计文件夹中所有文件的行数
【发布时间】:2017-06-21 14:16:46
【问题描述】:

我正在使用带有 python 2.7 的 Ubuntu,

我需要获取一个文件夹中的所有文件,并分别计算每个文件中的行数并将其转储到一个文件中。

我找到了如何通过终端直接使用并行处理here

当我尝试时它崩溃了:

subprocess.Popen('ls %s* | parallel -k zcat {} | wc -l >%s'%(dir,outputfile), shell=True)

现在我正在尝试通过 python 使用该终端命令, 似乎它无法获取文件列表并将它们用作文件,而只能计算文件列表的长度。

p1 = subprocess.Popen(["ls", dest], stdout=subprocess.PIPE)
    output = subprocess.check_output(["wc", "-l"], stdin=p1.stdout)

当我想要每个文件中有多少行的列表时,给我文件夹中的文件数。

我如何使用 python 来执行一个命令: 给我一个文件夹中每个文件有多少行的列表,并将使用并行(或任何其他好的多核方法)来完成

【问题讨论】:

  • 在unix shell中一行就可以解决

标签: python bash python-2.7 ubuntu terminal


【解决方案1】:

您可以使用标准库中的东西而无需掏腰包:

导入操作系统

from multiprocessing import Pool

folder = '.'

fnames = (name for name in os.listdir(folder)
          if os.path.isfile(os.path.join(folder, name)))


def file_wc(fname):
    with open(fname) as f:
        count = sum(1 for line in f)
    return count


pool = Pool()

print(pool.map(file_wc, list(fnames)))

如果要记录文件名

def file_wc(fname):
    with open(fname) as f:
        count = sum(1 for line in f)
    return (fname, count)

print(dict(pool.map(file_wc, list(fnames))))

【讨论】:

  • 使用 bash 背后的想法是已经实现了多核和优化,速度更快
【解决方案2】:

计算文件夹中的文件、目录和路径

import os

path, dirs, files = os.walk("/home/my_folder").next()
file_count = len(files)

计算文件中的行数,我试图找到一种方法在不打开文件的情况下计算行数,但我不能

with open(<pathtofile>) as f:
    print len(f.readlines())

现在您有了文件列表(第一个示例中的变量文件),您只需加入这 2 段代码即可获取变量文件中每个文件的行数

【讨论】:

    【解决方案3】:

    实际上你不需要使用外部进程在 python 中完成这项任务。 Python 可以为您完成。这是python3 sn-p:

    import os
    
    for x in os.listdir(): 
        if os.path.isfile(x):
            with open(x, 'rb') as f:
                print('{} lines: {}'.format(x, sum(1 for line in x)))
    

    这里有一些关于listening files in dirgetting number of lines in filecounting lines for huge files 的附加信息

    【讨论】:

      【解决方案4】:

      您可以将多处理与系统调用一起使用。您不必在这里使用队列,只需直接打印结果即可。

      import multiprocessing as mp
      from subprocess import Popen, PIPE
      
      
      output = mp.Queue()
      
      
      def count_lines(path, output):
          popen = Popen(["wc", "-l", path], stdout=PIPE, stderr=PIPE)
          res, err = popen.communicate()
          output.put(res.strip())
      
      
      popen = Popen(["ls", "."], stdout=PIPE, stderr=PIPE)
      res, err = popen.communicate()
      
      
      processes = [mp.Process(target=count_lines, args=(path.strip(), output)) for path in res.split('\n') if path]
      
      # Run processes
      for proc in processes:
          proc.start()
      
      for proc in processes:
          proc.join()
      
      
      results = [output.get() for proc in processes]
      non_empty = [result for result in results if result]
      print(non_empty)
      

      参考:

      https://sebastianraschka.com/Articles/2014_multiprocessing.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-28
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 2020-09-09
        • 2021-06-18
        相关资源
        最近更新 更多