473,756 Members | 6,106 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ls files --> list packer

I would like to use the power of Python to build some list structures
for me.

Namely i have organized a bunch of folders that have soundfiles in them
and would like Python to slurp up all the .aif/.aiff (or .wav whatever)
files in a given set of directories. My friend hacked up this is perl:

$files = `ls /snd/Public/*.aiff`;

@snd_filelist = split('\n',$fil es);

$i = 0;
while ($file = @snd_filelist[$i]) {
print "file $i = @snd_filelist[$i]\n";
$i++;
}
The only catch with the above code (besides its hideousness hee hee) is
if you have a directory w/i the structure, but in general it works and
with this i can just put gobs of files into separate dirs pack them
into a list and then send them to my script that scrambles them and
plays them.

I would like something similar, that works with python that is more
elegant and maybe even more robust.

but i am failing miserably and my perl friends mock me.

cheers,
kp8

Feb 24 '06 #1
14 2922
and one example of a slightly fancier version would be a variation that
looks recursively into subdirectories and makes separate lists for each
subdirectory encountered.

so if i had a directory called "~/snd/"

and in "~/snd/" i had:

"~/snd/one/"
"~/snd/two/"
"~/snd/three/"

each with soundfiles in it.

I could get those packed in three separate lists named after the
directory or some such thing....

This would be so awesome because my carefully organizing your
directory, you would be carefully
organizing your data, change your dir structure or add/delete some
files and you would get a new structure in your script... prolly would
work with scripting your iTunes music folder too...

gosh ... sorry ... just thinking out-loud here and getting kind of
giddy! reaching for the python book ...

Feb 24 '06 #2
I V

kpp9c wrote:
Namely i have organized a bunch of folders that have soundfiles in them
and would like Python to slurp up all the .aif/.aiff (or .wav whatever)
files in a given set of directories. My friend hacked up this is perl:

$files = `ls /snd/Public/*.aiff`;
You could use posix.popen to duplicate the perl hack:

files = posix.popen('ls /snd/Public/*.aiff').read() .strip()
@snd_filelist = split('\n',$fil es);
snd_filelist = files.split('\n ')
I would like something similar, that works with python that is more
elegant and maybe even more robust.
Lucklily, python lets you avoid this kind of horrible hack. Try
os.listdir:

snd_filelist = [f for f in os.listdir('/snd/Public/') if
f.endswith('.ai ff')]

I think it's more elegant, and it's certainly more robust.
but i am failing miserably and my perl friends mock me.


Now you get to mock your perl friends!

Feb 24 '06 #3
cool i just tried:
import os
snd_fileli st = [f for f in os.listdir('/Users/foo/snd') if f.endswith('.ai f')]

and it worked! and will take a huge bite out of my big script ... which
i make by doing an ls
in the terminal and editing (boo hoo)

one one lc and one import!

cool..

that other sillyness i mentioned is not strickly required ... just
dreaming but i know involves some kind of os walk type thing prolly ...
meanwhile this is so exciting!

Thank you!!!!

Feb 24 '06 #4
gosh i could even use other string methods like startswith to take all
the files in a given directory which i have organized with a prefix and
have them stuffed in different lists ... i think ...

snd_filelist = [f for f in os.listdir('/Users/foo/snd') if
f.endswith('.ai f') & f.startswith('r ')]

\m/ (>.<) \m/

yeah!

runnin' to the interpreta now...

Feb 24 '06 #5
I V wrote:
snd_filelist = [f for f in os.listdir('/snd/Public/') if
f.endswith('.ai ff')]


Or even

from glob import glob

snd_filelist = glob('/snd/Public/*.aiff')

Jeremy

--
Jeremy Sanders
http://www.jeremysanders.net/
Feb 24 '06 #6
Try using The Path module:
http://www.jorendorff.com/articles/python/path/.

I wrote a little script to traverse a directory structure which you
could use. (You just pass a function to it and it runs it on each file
in the directory. You want it to run on each directory instead, so
I've changed it a little for you).

import path

def traverse(direct ory, function, depth=0, onfiles=True, ondirs=False):
thedir = path.path(direc tory)
if onfiles == True:
for item in thedir.files():
function(item, depth)
if ondirs == True:
for item in thedir.dirs():
function(item, depth)
for item in thedir.dirs():
traverse(item, function, depth+1, onfiles, ondirs)

You can use it like so:

def printaifs(thedi r, depth):
print thedir.name
for item in thedir.files("* .aif'"):
print "\t" + item

traverse(r"/Users/foo/snd", printaifs, onfiles=False, ondirs=True)

NB: I've quickly adapted this whilst away from an installation of
Python, so it is untested, but should mostly work, unless there's a
typo.

Hope this helps at least a little...

Ed

PS The Python Tutor list tends to be a much better place to discuss
this kind of stuff. If you haven't yet encountered Kent and Alan's
help, then you have a joyous experience ahead of you.

Feb 24 '06 #7
kpp9c wrote:
that other sillyness i mentioned is not strickly required ... just
dreaming but i know involves some kind of os walk type thing prolly ...


os.walk isn't exactly rocket science... Something similar to this?
import os
for dir, dirs, files in os.walk('.'):

.... txt_files = [x for x in files if x.endswith('.tx t')]
.... if txt_files:
.... print dir, txt_files
Feb 24 '06 #8
that is nice.... but the little further wrinkle, which i have no idea
how to do, would be to have the contents of each directory packed into
a different list.... since you have no idea before hand how many lists
you will need (how many subdirs you will enounter) ... well that is
where the hairy part comes in...

-kp--

Feb 24 '06 #9
os.listdir works great ... just one problem, it packs the filenames
only into a list... i need the full path and seach as i might i se NO
documentation on python.org for os.listdir()

how do i either grab the full path or append it later ...

Feb 27 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1079
by: Grant Edwards | last post by:
Could whoever is gatewaying this group to a mailing list PLEASE fix whatever problem is causing Usenet posters to receive bounce messages and out-of-office messages from subscribers to your service? When I post an article to Usenet _I_DONT_CARE_ if your gateway has problems mailing that article to somebody. I DON'T WANT TO BE NOTIFIED that somebody I've never heard of in Poland is out of his office and that somebody else in Slovakia...
10
1404
by: jamesthiele.usenet | last post by:
I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = , x) for x in os.walk(".")] filenames = for dir, files in walkList: filenames.extend() for f in files]) It works fine, I don't need to change it, but I know there is a one liner list/generator comprehension to do this - I'm just not well
8
53691
by: dp | last post by:
Is there anyway to have the bullet color of a <li> be a different color than the text without using an image? dp
5
2201
by: Konrad L. M. Rudolph | last post by:
I hope this is the right NG, please notify me if not. I have got a problem with the "recent files" list of the start page in VS.NET: yesterday I created a new projekt which has the same name as an already existing project stored at another location. Unfortunately, VS.NET doesn't seem to support double names in the "recent files" list: only /one/ entry with the double name is listed and even more unfortunate, it is the one which I don't...
3
3175
by: Michael | last post by:
X-Replace-Address Hello, I am trying to write a program at work for reading/writing files larger than 4 GB. I know that Windows supports files that big but I have not been able to get my program to write past the 4 gig boundary. Some solutions that I have tried:
3
1550
by: Gregor Horvath | last post by:
Hi, given the dynamic nature of python I assume that there is an elegant solution for my problem, but I did not manage to find it. I have a file that contains for example on line: when I read the file
4
2368
by: VK | last post by:
I'm looking for autoexpand <select> list onfocus and collapse it back onselect/onblur (the list is select-one type) I know it is not possible directly, but I've seen here a hack by changing dynamically position static/absolute and sel.size - cannot google it out though. Also some GNU/copyleft widget would be equally great.
4
3740
by: zacks | last post by:
Most applications whose purpose is to work with various types of files implement a "Most Recent Files" list, where the last, say, four files accessed by the application can quickly be re-opened by clicking on the file name in the File menu. Thist list is usually just above the typical Exit menu item. I take it there is no "automatic" way of implementing this, that each application has to have code that manually does this. I have a good...
1
2971
by: jollyguy77 | last post by:
Hi, I have just started to learn in .net. I want to show a list of filename along with the corresponding image (like pdf image for pdf files etc..). i will be getting the list of files from database. I want to show the files in list view format and also give the option for the user to change the view to details or thumbnail or icons accordingly.. also to give the option for renaming or deleting a file. I know that there is a Listview...
0
9454
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10028
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9868
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9836
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9707
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7242
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3804
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2664
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.