Looping through files in a folder

前端 未结 3 744
我在风中等你
我在风中等你 2021-01-01 09:20

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

What I want to do is to recolour sprites for a game, and I am given the original

相关标签:
3条回答
  • 2021-01-01 09:52
    for pix in filename:
    

    iterates over the letters of the filename. So that's certainly not what you want. You'll probably want to replace that line by:

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

    (assuming Python 2.6) and indent the rest of the loop accordingly.

    However, I'm not sure that the new for loop does what you want unless by pix you mean a line of text in the current file. If the files are binary picture files, you'll first need to read their contents correcty - not enough info in your post to guess what's right here.

    0 讨论(0)
  • 2021-01-01 10:02

    The path is wrong because the backslashes need to be doubled up - backslash is an escape for special characters.

    os.listdir does not return open files, it returns filenames. You need to open the file using the filename.

    0 讨论(0)
  • 2021-01-01 10:09

    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.

    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')
    
    0 讨论(0)
提交回复
热议问题