2017-02-28 32 views
3

我想对子目录中的所有文件执行操作,并将输出放在另一个目录中。例如,在/图片/有subdirs/1月,/ 2月/等,在他们imgages。我想对/加工/及其子目录/月,/ 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 

回答

1

这应该给你的基本结构:

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'

0

这基本上遍历目录的所有文件夹,获取它的文件;用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() 

希望它有帮助!

相关问题