首页 > 解决方案 > 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"

标签: pythonloops

解决方案


使用重命名?

import os

os.mkdir("new_folder")

for file in ['file1.txt', 'file2.txt']:

    os.rename(file,f'new_folder/{file}')

推荐阅读