循环子目录中的文件并将输出放在其他子目录中

2024-10-03 23:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对子目录中的所有文件执行一个操作,并将out放入另一个目录。例如,在/Pictures/中有subdirs/一月、/二月等,其中有imgages。我想对图像执行操作,并将输出放到/Processed/及其子目录/January、/Februady等

我想这样的问题可以解决,但我真的需要一些帮助:

import os
path = '/Pictures/'
outpath = '/Processed/'
for subdir, dirs, files in os.walk(path):
    #do something with files and send out put to corresponding output dir

Tags: 文件path图像import目录osfilesout
2条回答

这基本上是遍历一个目录的所有文件夹,得到它的文件;使用performFunction()执行一些操作并写入同一个文件您可以修改它以写入不同的路径

def walkDirectory(directory, filePattern):
    for path, dirs, files in os.walk(os.path.abspath(directory),followlinks=True):
        for filename in fnmatch.filter(files, filePattern):
         try:
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            s = performFunction()

            with open(filepath, "w") as f:
                print filepath
                f.write(s)
                f.flush()
            f.close()
         except:
           import traceback
           print traceback.format_exc()

希望有帮助

这将为您提供基本结构:

import os
path = 'Pictures/' # NOTE: Without starting '/' !
outpath = 'Processed/'
for old_dir, _, filenames in os.walk(path):
    new_dir = old_dir.replace(path, outpath, 1)
    if not os.path.exists(new_dir):
        print "Creating %s" % new_dir
        os.makedirs(new_dir)
    for filename in filenames:
        old_path = os.path.join(old_dir, filename)
        new_path = os.path.join(new_dir, filename)
        print "Processing : %s -> %s" % (old_path, new_path)
        # do something with new_path

它在'Processed/'中创建与'Pictures/'中相同的子文件夹结构,并对每个文件名进行迭代

对于文件夹中的每个文件,都会得到new_path变量:

old_path'Pictures/1/test.jpg'new_path将是'Processed/1/test.jpg'

相关问题 更多 >