Newbie problem with user input

Steve Holden sholden at holdenweb.com
Wed Jul 11 10:48:02 EDT 2001


"Chris McMillan" <christopherjmcmillan at eaton.com> wrote in message
news:9ihit4$8r611 at interserv.etn.com...
> Hello all!  The partial code below prompts a user to enter a path.  I then
> want it to find (and later do something with) all the files in that
> directory matching the specified string.  The problem is that when I run
the
> script, and enter, for example D:\test it does not find any of the files.
I
> believe it is because the glob command is searching for
''D:\\test'\\*.dat'
> With the extra single quotes.  How can I get it to search for
> 'D:\\test\\*.dat' ?  Thanks!
> Chris
>
>
> print 'Enter the path:'                  # prompt user for directory path
> path = raw_input()
> for fname in glob.glob('path\\*.dat'):   # finds files matching string
>

Your diagnosis of the problem is incorrect: when you provide input to
raw_input(), what you type (less the newline) is what the function returns.
Backslash characters are not treated specially. You have probably been
confused by seeing the interpreter output when you ask it to evaluate

      path

as an expression. Here's a commented session which shows you that the
interpreter sometimes tries to "help" by printing the string in an
unabiguous way. The print command shows you what's actually in there.

>>> path = raw_input("Path:")
Path:D:\test    # I typed what you typed
>>> print path
D:\test        # print shows you what's in the string ...
>>> print str(path)
D:\test        # ... because it uses str() to get strings
>>> print repr(path)
'D:\\test'    # repr() gives you something you can paste into a program ...
>>> path
'D:\\test'    # ... the interpreter uses repr() after evaluating an
expression


You are not using the value of the path variable in your glob argument, so
you are actually globbing for files which match the pattern

    path\*.dat

Change the last line to

for fname in glob.glob(path+'\\*.dat'):   # finds files matching string

and you will probably find it works much better. This adds "\\*.dat" to the
end of whatever you type in.

If you are interested in portability (which you may not be) the the os.path
module contains functions which can help you to work with file paths.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list