循环浏览文件夹中的文件 [英] Looping through files in a folder

查看:85
本文介绍了循环浏览文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编程方面,我还很陌生,并且已经开始学习python.

I'm fairly new when it comes to programming, and have started out learning python.

我想要做的是为游戏的精灵重新着色,我得到了原始的颜色, 其次是将它们变成什么.每个精灵都有20到60个角度,所以 遍历每种颜色的文件夹中的每个文件夹可能是适合我的方法. 我的代码就这样了;

What I want to do is to recolour sprites for a game, and I am given the original colours, followed by what they are to be turned into. Each sprite has between 20 and 60 angles, so looping through each one in the folder for each colour is probably the way to go for me. My code goes thusly;

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作为字符串值(它们都是图片)上总是出错.

But I keep getting an error on the pathname, and on pix being a string value (They're all pictures)

任何帮助表示赞赏.

推荐答案

os.listdir()返回文件名列表.因此,filename是一个字符串.我猜,您需要先打开文件,然后再进行迭代.

os.listdir() returns a list of file names. Thus, filename is a string. You need to open the file before iterating on it, I guess.

此外,请注意字符串中的反斜杠.它们主要用于特殊的转义序列,因此您需要通过将它们加倍来对其进行转义.您可以使用常量os.sep使其更具可移植性,甚至可以使用os.path.join():

Also, be careful with backslashes in strings. They are mostly used for special escape sequences, so you need to escape them by doubling them. You could use the constant os.sep to be more portable, or even use os.path.join() :

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

这篇关于循环浏览文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆