简体   繁体   中英

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, ie

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

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

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

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']
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM