tags:

views:

92

answers:

4

Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.

Thanks

+1  A: 

~ is expanded by the shell and not a real path. As such you have to navigate there manually.

import os

homeDir = os.environ['HOME']
f = open( homeDir + '/.mozilla/firefox/*.default' )
# ...
poke
That doesn't quite work. The asterisk is a wild card, not a part of the name.
Jonah Bron
Oh, didn't notice that.
poke
A: 

http://docs.python.org/library/os.html Gives a complete reference if you would like to change directory or give paths.

You can for example give relative paths and access specific files.

If you would like to execute commands then http://docs.python.org/library/commands.html provides nice wrappers for the os.popen() function

anijhaw
+6  A: 

This

import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))

will give you a list of all files ending in ".default" in the current user's ~/.mozilla/firefox directory using os.path.expanduser to expand the ~ in the path and glob.glob to match the *.default file pattern.

Will McCutchen
Thanks! That's perfect. Then I can use $your_code[0] and get any files I want in that directory.Sorry I can't vote up your answer, I don't have enough reputation.
Jonah Bron
A: 

It's important to remember:

  • use of the tilde ~ expands the home directory as per Poke's answer
  • use of the forward slash / is the separator for linux / *nix directories
  • by default, *nix systems such as linux for example has a wild card globbing in the shell, for instance echo *.* will return back all files that match the asterisk dot asterisk (as per Will McCutcheon's answer!)

Hope this helps, Best regards, Tom.

tommieb75