2017-03-27 50 views
0

我有一個腳本,我想運行目錄中的所有文件。我可以找到的所有示例使用我知道的文件不再適用於python 3.x.如何爲目錄中的多個文件運行腳本?

原來這就是我意識到,之前嘗試過:

import sys, os, cv2 

path = 'C:\\Users\\telli\\Desktop\\Test Shapes\\Shapes\\Squares' 

for filename in os.listdir(path): 
    for file in files: 
     if file.endswith('.jpg'): 
      os.system ('C:\\Users\telli\\Desktop\\test.py {}'.format(root + '\\' + file)) 

所以我應該將其更改爲?我已經看到使用open,但我不確定熱。

你也可以告訴我一行代碼,將省略主文件夾中的某個文件/文件夾?

我試過,但沒有任何反應:

import sys, os 

path = 'C:\\Users\\telli\\Desktop\\Test Shapes\\Shapes\\Squares' 

for file in os.listdir(path): 
    if file.endswith('.jpg'): 
     img = cv2.imread(file) 
     #print(img) 

     #Converting the image to Grayscale 
     grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

     ret,thresh = cv2.threshold(grey,127,255,1) 

     im2,contours, h = cv2.findContours(thresh, 1, cv2.CHAIN_APPROX_SIMPLE) 
     contours.sort(key = len) 

     cv2.imshow('img',img) 
     cv2.waitKey(0) 
     #os.system('C:\\Users\telli\\Desktop\\test.py {}'.format(root + '\\' + file)) 

感謝

+1

什麼實際的問題,你遇到? – smarx

+0

python 2'file'函數在這裏沒有被使用...這個代碼應該在Python 3中工作(至少,這個問題不會是'file'函數) –

+0

爲什麼內部循環?那是你的問題。只需使用'for os.listdir(path)'中的文件'並刪除內部循環。 –

回答

0

嘗試glob模塊。

import glob 
path = 'C:/Users/telli/Desktop/Test Shapes/Shapes/Squares' 
filenames = glob.glob(path + '/*.gif') 
for filename in filenames: 
    # Do something 

留下了一個文件之一:

  • if語句在for循環忽略文件添加一個你不想
  • 改變你的水珠,只選擇你想要的文件

eg

>>ls 
this_is_a_good_file.gif 
this_is_a_good_file_2.gif 
this_is_a_bad_file.gif 

glob.glob(path + '/*good*.gif') 

將排除 'this_is_a_bad_file.gif'

相關問題