【问题标题】:how to perform a task on every file in a folder python如何对文件夹python中的每个文件执行任务
【发布时间】:2013-07-09 13:58:54
【问题描述】:

我已经生成了许多文本文件,它们都包含一个浮点数列表。每个列表的长度因文件而异。我想为每个文件生成一个直方图。因此,我想遍历目录中的所有 txt 文件并为每个文件打印一个直方图。到目前为止,我已经尝试过这段代码,但无济于事:

for file in list(glob.glob('*.txt')):
    with open(file, 'r') as f:
        numbers = f.read().strip()
        n, bins, patches = hist(numbers, 100, normed=1, histtype='bar')
        setp(patches, 'facecolor', 'g', 'alpha', 0.75)
        title('m_score for each complex spike')
        ylabel('number of complex spikes')
        xlabel('m_score')
        show()

我也试过用:

for line in fileinput.input(glob('*.txt')):

但在这里我只能生成一个直方图。任何帮助将不胜感激,我一直在努力迭代文件。

【问题讨论】:

  • 您列出的第一个代码示例到底有什么问题?

标签: python loops histogram


【解决方案1】:

您可以使用os.listdir() (http://docs.python.org/2/library/os.html#os.listdir) 获取给定目录中的所有文件;然后您可以遍历所有文件并获取数据。

在您发布的代码中,您似乎在每次迭代中都覆盖了patches,这可能就是您只得到一个直方图的原因。

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    import os
    
    directory = os.path.join("/","path") # directory that contains your files
    for root,dirs,files in os.walk(directory):
        for file in files:
           if file.endswith(".txt"):
               with open(file, 'r') as f:
                   numbers = f.read().strip()
                   n, bins, patches = hist(numbers, 100, normed=1, histtype='bar')
                   setp(patches, 'facecolor', 'g', 'alpha', 0.75)
                   title('m_score for each complex spike')
                   ylabel('number of complex spikes')
                   xlabel('m_score')
                   show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多