[Chicago] Reading From a Directory

Clyde Forrester clydeforrester at gmail.com
Tue May 10 02:01:32 CEST 2011


Sean Brant wrote:
> On May 9, 2011, at 6:32 PM, Clyde Forrester wrote:
> 
>> What I want to do is open a directory and read file names from it.
>>
>> The standard answer I get by Googling seems to be:
>> No you don't. Are you mad? Why would you want to do that? Clearly you want to do something else. It's a scripting language and you have no business "programming" in it. Why don't you just pass the buck to a shell (os.popen) and handle it that way? Or use a magic module glob.glob) to get a complete list, or something.
>>
>> Perl and Ruby have directory classes with open, read, and close methods. Why doesn't Python?
>>
>> Now it does occur to me that any time I want to read from a directory, I want all the files. Even if I'm using a wild card, I want to apply it to all the files in the directory, not just the first one or two. But somehow calling out to a shell, or invoking a module seems as "easy" as hiring a subcontractor to tie my shoes. I don't things have to get that complicated.
> 
> If you just need to list the files in a directory do os.listdir [1]. If need Unix style shell matching use the glob module [2].
> 
> [1] http://docs.python.org/library/os.html#os.listdir
> [2] http://docs.python.org/library/glob.html
> 
>> c4

Thank you, Sean, Dan, JongMan, Dan, Mike, and Carl.

It seems that os.listdir and glob are, in fact, the properly Pythonic 
ways of going about it. Outsourcing something that fundamental to a 
shell or module still bugs me, but I think I have to adapt my way of 
thinking to the more pragmatic viewpoint.

As Carl pointed out:

> My guess is you want the list of files in a dir, and don't care how
> that happens.

Again, thank you.


More information about the Chicago mailing list