2009-11-24 88 views
32

我在編程方面相當新,並且已經開始學習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是一個字符串值(他們都是圖片)

任何幫助表示讚賞。

+0

你可以顯示你收到的具體錯誤信息嗎? – perimosocordiae 2009-11-24 19:24:22

+0

這是一個學校作業嗎?我在「媒體」模塊上從Google獲得的所有搜索結果似乎都表明它是...... – 2009-11-24 19:28:11

回答

3

路徑是錯誤的,因爲反斜槓需要翻倍 - 反斜槓是特殊字符的轉義。

os.listdir不返回打開的文件,它返回文件名。您需要使用文件名打開文件。

34

os.listdir()返回文件名列表。因此,filename是一個字符串。我想,在迭代之前需要打開文件。

此外,請小心字符串中的反斜槓。它們主要用於特殊的轉義序列,所以你需要通過加倍來逃避它們。你可以使用常量os.sep更輕便,甚至可以使用os.path.join()

folder = os.path.join('C:\\', 'Users', 'Sprinting', 'blue') 
10
for pix in filename: 

遍歷文件名中的字母。所以這當然不是你想要的。您可能想要替換該行:

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

(假設Python 2.6)並相應縮進循環的其餘部分。

但是,我不確定新的for循環做什麼,除非通過pix您是指當前文件中的一行文本。如果文件是二進制圖片文件,你首先需要閱讀他們的內容correcty - 沒有足夠的信息在你的文章猜猜這裏是什麼。

相關問題