【发布时间】:2017-03-29 21:10:50
【问题描述】:
我正在使用 python 和 matplotlib 从相当大的 XY 数据数据库(约 1000 个文件夹并且还在增长)生成绘图。每个文件夹都包含一个 CSV 文件,其中包含我要生成散点图的 XY 数据。 由于会定期将更多数据文件夹添加到根文件夹中,因此我想定期运行我的脚本以保持绘图更新。不幸的是,这个脚本现在运行了大约 10 分钟,我预见它会运行得越来越长。
如果文件夹中存在 .png 文件,我想通过在我的代码中添加一些内容来加快脚本速度,这样会跳过在当前文件夹中搜索 XY 数据。我应该对下面的代码进行哪些修改以反映这一点?
import os
import matplotlib.pyplot as plt
# Find files containing XY data
for root, dirs, files in os.walk('D:/temp\\', topdown=False):
for name in files:
#find and check txt file
if name.startswith('XY') and name.endswith('.txt'):
# read data and store lines in list
try:
posX = list() #list of x-positions
posY = list() #list of y-positions
filepath = os.path.join(root, name)
fp = open(filepath)
for line in fp:
# make lists from the csv rows
content = line.split()
posX.append(float(content[0]))
posY.append(float(content[1]))
fp.close()
# prepare a scatter plot
figure = plt.scatter(posX,posY)
# save plot as png
plt.savefig(root+'plot.png')
# clear plot data for next for loop iteration
plt.clf()
更新: 使用下面的答案,我更新了第二个 for 循环中的 if 语句:
#find and check txt file
if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root+'plot.png'):
(...)
else:
print('no new data available')
【问题讨论】:
标签: python python-2.7 matplotlib plot