遍历文件夹中的文件

35 投票
3 回答
64764 浏览
提问于 2025-04-15 16:20

我刚开始学习编程,正在学Python。

我想做的是给游戏里的角色图像换颜色,已经有了原来的颜色和要换成的颜色。每个角色图像有20到60个角度,所以我觉得可以通过循环文件夹里的每个图像来处理每种颜色。

我的代码是这样的;

import media
import sys
import os.path

original_colors = str(raw_input('Please enter the original RGB component, separated ONLY by a single space: '))
new_colors = str(raw_input('Please insert the new RGB component, separated ONLY by a single space: '))
original_list = original_colors.split(' ')
new_list = new_colors.split(' ')
folder = 'C:\Users\Spriting\blue'
if original_colors == 'quit' or new_colors == 'quit':
    sys.exit(0)
else:
    while 1:
        for filename in os.listdir (folder):
            for pix in filename:
                if (media.get_red(pix) == int(original_list[0])) and (media.get_green(pix) == int(original_list[1])) and \
                   (media.get_blue(pix) == int(original_list[2])):
                    media.set_red(pix, new_list[0])
                    media.set_green(pix, new_list[1])
                    media.set_blue(pix, new_list[2])

                    media.save(pic)

但是我总是遇到路径名的错误,还有就是pix被当成了字符串(它们都是图片)。

希望能得到一些帮助。

3 个回答

3

路径写错了,因为反斜杠需要写两个 - 反斜杠是用来表示特殊字符的。

os.listdir 这个函数不会返回打开的文件,它只会返回文件名。你需要用文件名去打开文件。

10
for pix in filename:

这段代码是用来逐个处理文件名里的字母的。所以这肯定不是你想要的。你可能想把那一行换成:

with open(filename) as current_file:
    for pix in current_file:

(假设你用的是Python 2.6),然后相应地调整循环的缩进。

不过,我不太确定新的for循环是否能满足你的需求,除非你说的pix是指当前文件中的一行文本。如果这些文件是二进制图片文件,你首先需要正确读取它们的内容——你发的内容里没有足够的信息让我猜测该怎么做。

35

os.listdir() 这个函数会返回一个文件名的列表。所以,filename 是一个字符串。在你想要处理这个文件之前,得先把它打开。

另外,字符串中的反斜杠要小心使用。反斜杠通常用来表示一些特殊的转义序列,所以你需要通过把它写成两个反斜杠来进行转义。为了让代码更通用,你可以使用常量 os.sep,或者直接使用 os.path.join() 来处理路径:

folder = os.path.join('C:\\', 'Users', 'Sprinting', 'blue')

撰写回答