0

我正在创建一个小脚本来自动将文件从 .jpg 转换为 .png:

import glob, os
import Image

basedir = "C:\Users\User\Desktop\\fimg\images\\"
prefix  = "picture"

def convert_png():
    for jpg in glob.glob(os.path.join(basedir, '*.jpg')):
        filename = f.rsplit('.')[-2]
        njpg = Image.open(basedir + '%s.jpg' % (filename))
        njpg.save(basedir + '%s.png' % (filename))

        print "CONVERTED: " + filename + '.png'

for i, f in enumerate(os.listdir(basedir), 1):
    convert_png()

但是有了这个,它似乎会多次转换文件(大约 10 次),因为它会打印这个数量的转换后的消息,然后再移动到下一个文件。这里有什么问题导致它这样做吗?

C:\Users\User\Desktop\fimg>python test.py
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
4

1 回答 1

1
import glob, os
import Image

basedir = "C:\Users\User\Desktop\\fimg\images\\"
prefix  = "picture"

def convert_png(base):
    njpg = Image.open(basedir + '%s.jpg' % base)
    njpg.save(basedir + '%s.png' % base)
    print "CONVERTED: " + base + '.png'

for i, f in enumerate(os.listdir(basedir), 1):
    base, ext = os.path.splitext(f)
    if ext == '.jpg': # found jpg file
        convert_png(base)

问题在于嵌套循环:底部for,然后调用convert_png,它本身有另一个循环。我消除了循环,convert_png并通过仅在找到具有.jpg扩展名的文件时调用该函数来稍微简化代码。请注意使用splitext将文件名拆分为其基础和扩展名。

于 2012-05-25T22:31:33.847 回答