2017-03-29 45 views
0

我正在使用python和matplotlib從XY數據(〜1000文件夾和增長)的相當大的數據庫生成繪圖。每個文件夾都包含一個包含XY數據的CSV文件,我想要生成散點圖。 由於更多數據文件夾被定期添加到根文件夾,我想定期運行我的腳本以保持繪圖更新。不幸的是,這個腳本現在運行了大約10分鐘,我預測它會持續運行時間越來越長。繪圖生成:如果圖已經存在,則停止for-loop

我想通過向代碼添加一些東西來加速腳本,如果文件夾中存在.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') 

回答

0

所有你需要的是從英文你原來的問題翻譯成Python:

if name.startswith('XY') and name.endswith('.txt') \ 
    and not os.path.isfile(root+'plot.png'): ... 
0

您可以使用

import os 
os.path.isfile(fname) 

如果你的情節存在,你知道,一個名爲

root + 'plot.png' 

必須在當前目錄。如果你想擺脫你的for循環的使用關鍵字

break 
+0

確定這是非常明確的,它工作

if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root + 'plot.png'): 

: 可以因此添加到您,如果句子。感謝您指出了這一點! – skleijn

相關問題