如何对python文件夹中的每个文件执行任务
我已经生成了许多文本文件,它们都包含一个浮动列表。每个列表的长度因每个文件而异。我想为每个文件生成一个直方图。因此,我想迭代一个目录中的所有txt文件,并为每个文件打印一个直方图。到目前为止,我已尝试过此代码,但没有效果:如何对python文件夹中的每个文件执行任务,python,loops,histogram,Python,Loops,Histogram,我已经生成了许多文本文件,它们都包含一个浮动列表。每个列表的长度因每个文件而异。我想为每个文件生成一个直方图。因此,我想迭代一个目录中的所有txt文件,并为每个文件打印一个直方图。到目前为止,我已尝试过此代码,但没有效果: for file in list(glob.glob('*.txt')): with open(file, 'r') as f: numbers = f.read().strip() n, bins, patches = hist(nu
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')):
但这里我只能生成一个直方图。任何帮助都将不胜感激,我一直在努力迭代文件。您可以使用
os.listdir()
()获取给定目录中的所有文件;然后,您可以迭代所有文件并获取数据
似乎在您发布的代码中,您在每次迭代中都覆盖了
补丁
,这可能就是您只得到一个直方图的原因。您可以尝试以下方法:
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()
对于您列出的第一个代码示例,什么不起作用?