[Tutor] I need help slicing.

Jeff Shannon jeff@ccvcorp.com
Fri, 12 Jul 2002 11:52:54 -0700


SA wrote:

> I would like to compare each string individually and do a conditional
> statement that says how to handle the file. In other words, I would like my
> script to individually discern between the .txt file and the .html file and
> handle each file differently based upon it's file extension.
> [...]
> On another note, say it has a directory in front of the file, I would like
> the script to look at the directory name and decide whether it is ok or not
> to continue on working on this file.

If you're manipulating filenames and paths, then you should probably use the
os.path module.

>>> import os
>>> os.path.join('c:\\temp', 'subdir', 'file.txt')
'c:\\temp\\subdir\\file.txt'
>>> fname = 'c:\\temp\\textfile.txt'
>>> os.path.splitext(fname)
('c:\\temp\\textfile', '.txt')
>>> os.path.split(fname)
('c:\\temp', 'textfile.txt')
>>> os.path.dirname(fname)
'c:\\temp'
>>>

This should give you the tools you need to isolate the various parts of the
file/path names that you want to compare.

However, you can also easily do this sort of thing with negative-index string
slicing.

>>> fname
'c:\\temp\\textfile.txt'
>>> fname[-4:]
'.txt'

But, for what you're doing, the os.path functions will be a much more robust
and flexible way of doing things.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International