Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read file names from directory w/ python

I'm trying to make a pygame executable. I will use the following setup file:

from distutils.core import setup
import py2exe

setup( 
  console = [ "game.py" ],
  author = "me",
  data_files = [ ( directory, [ file_1, file_2... ] ) ]
)

I've gotten this to work fine on a simple game, but the game I want to package up has > 700 image files. My question is, is there a simple way to read all file names from a directory so I don't have to list each one separately?

While there are some files that are numbered in sequence, most have a different root name, so writing a loop that makes the appropriate strings is not an option.

Thanks

like image 537
sabajt Avatar asked Dec 04 '22 21:12

sabajt


1 Answers

import os

data_files = [(x[0], x[2]) for x in os.walk(root_dir)]

http://docs.python.org/library/os.html#os.walk

This will give you the files for every subdirectory contained within root_dir (along with the ones in root_dir itself, of course) as tuples in the format [(dirpath1, [file1, file2, ...]), (dirpath2, [file3, file4, ...]), ...]

I gave you this as my answer because I'm assuming (or rather, hoping) that, with so many files, you're keeping them properly organized rather than having them all in a single directory with no subdirectories.


It's been a while, but coming back to this I now realize that for a long list of files, a generator expression would probably be more efficient. To do so, a very simple change is needed; replace the outer brackets with parentheses, i.e.

import os
data_file_gen = ((x[0], x[2]) for x in os.walk(root_dir))

And data_file_gen could then be used wherever data_files was iterated over (assuming you're only using the generator once; if the generator is to be used multiple times, you would have to recreate the generator for each use. In such cases it may be better to just use the list method unless memory does become a problem.).

like image 64
JAB Avatar answered Dec 07 '22 11:12

JAB