Python 如何为目录中的多个文件运行脚本?

Python 如何为目录中的多个文件运行脚本?,python,file,for-loop,directory,Python,File,For Loop,Directory,我有一个脚本,我想为目录中的所有文件运行它。我能找到的所有示例都使用我知道在Python3.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'):

我有一个脚本,我想为目录中的所有文件运行它。我能找到的所有示例都使用我知道在Python3.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))

谢谢

您遇到的实际问题是什么?这里没有使用python 2
文件
函数。。。这段代码应该在Python3中工作(至少,问题不在于
文件
函数)为什么要使用内部循环?这是你的问题。只需在os.listdir(path)
中为文件使用
,并删除内部循环。您遇到的实际问题是什么?这里没有使用Python2
file
函数。。。这段代码应该在Python3中工作(至少,问题不在于
文件
函数)为什么要使用内部循环?这是你的问题。只需在os.listdir(path)
中为文件使用
,并删除内部循环。