开发者

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


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.).


The os module has a method called listdir that takes a path and returns the contents as a list.


Try this

data_files = [directory, ...]  # whatever you want to put specifically.
data_files += [file for file in os.listdir('images') if os.path.isfile(file)]  # for adding your image files


Use glob to collect all files in a directory. Use . to collect all files, or *.jpg to collect all .jpg files. This will put the images in a folder called "Images" in your py2exe output directory.

...
from glob import glob
...
data_files = [
        ("Stuff", glob(r'C:\projectfolder\Stuff\*.*')) 
        ,("dlls", glob(r'C:\projectfolder\dlls\*.dll'))                  
        ,("Images", glob(r'C:\projectfolder\images\*.*'))  
         ]  
...
setup(
name='ProjectName'
,options = options
,data_files=data_files
,console=['projectname.py']
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜