Python逐个转换目录中的文件

2024-03-29 01:36:08 发布

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

如何使用下面的代码逐个转换目录中的所有文件

此代码获取文件夹中的所有文件并将其一起转换,但会占用太多内存。我需要在循环中分别为每个文件执行此操作

即查找文件。转换移动重复一遍

import os
import shutil
import glob
command = ('convert -compress LZW -alpha off -density 320 -depth 4 - 
contrast-stretch 700x0 -gamma .45455 *.pdf -set filename:base "% 
[basename]" +adjoin "%[filename:base].tiff"')

newpath = r'...'
new_dir = 'tiff'

if not os.path.exists(newpath):
    try:
        os.mkdir(new_dir)

    os.system(command)
except:
    print "The folder is already exist"


for file in glob.glob("*.tiff"):
    try:
        print('"' + file + '"' + ' has just moved to ' + '"' + new_dir + '"' + ' folder')
        shutil.move(file, new_dir);
    except:
        print "Error"

Tags: 文件代码importnewbaseosdirfilename