lists and files question

John Machin sjmachin at lexicon.net
Wed Jul 23 08:28:04 EDT 2003


hokiegal99 <hokiegal99 at hotmail.com> wrote in message news:<3F1DF318.20308 at hotmail.com>...
> "print fname" prints out the list of files in "setpath" w/o problem. How 
> does it do that if os.walk doesn't give it the path to the files?

If you do open('x.txt') and your current directory is (say) /tmp, it
will in effect be trying to open('/tmp/x.txt') which will presumably
fail with the error that you saw because there's no such file ...
hence Sean's advice to use os.path.join so that you are in effect
doing
open('/usr/hokiepokie/weird_files/x.txt')
thus opening the file that you want and does exist -- unless of course
some other process moved it or deleted it after the os.walk() and
before the open() --

This is not a Python thingy nor a Linux thingy; implicitly assuming
that a "short" filename is relative to the calling process's current
directory/folder/group/whatever has been accepted behaviour with any
hierarchical file system that I've ever seen.

Now answering your question:
fname contains (say) ['x.txt', 'foo.xls', 'bar.doc'] and root contains
(say) '/usr/hokiepokie/weird_files'. So of course
   print fname
manages to print 
   ['x.txt', 'foo.xls', 'bar.doc']
without reference to root, just as 
   zot = 42; print zot
manages to print
   42
without reference to root.


> 
> Here's some output from "print fname":
> 
> ['index.txt', 'CELL-MINUTES.xls', '.nautilus-metafile.xml']

... large chunks of your life history snipped ...

> Sheet.xls', 'application.pdf', 'budsum.pdf']
> 
> When I add os.path.join like this:
> 
> setpath = raw_input("Enter the path: ")
> for root, dirs, files in os.walk(setpath):
> 	id = re.compile('Microsoft Excel Worksheet')
> 	fname = files
> 	print fname
> 	content = open(os.path.join(root,fname[0]),'rb')
> 	
> I get a "IndexError: list index out of range" error.
> 
> This is a Linux 2.4 computer running Python 2.3b2... if that matters.

It's always good to tell the OS and Python version; however in this
case it doesn't matter.

Put your thinking cap on: "list index out of range" ... which list?
what was the value of the index? ... "in range" means 0 <= index <
length of list; which of those 2 constraints was violated? what does
that tell you?




More information about the Python-list mailing list