質問

I've written a program whose main thrust is to continually ask the user for data file names and then to graph those files. However, those files exist in various directories, by design. I decided it'd be nice to be able to navigate around in the standard cd style, so that the user can enter said directories easily and choose whichever files he/she wants.

I'm newish to python (and am using 2.7 right now), so maybe I've implemented this poorly, but what follows is my code right now:

import os

...

userinput = raw_input('What would you like to do: ').lower()
if userinput.startswith('cd '):
    try:
        newdir = userinput.split('cd ')[1]
        os.chdir(newdir)
        print(os.getcwd()+'\n')
    except:
        print('Not a valid directory.\n')

This actually works well for my test cases so far (running in a Windows environment, for better or worse), with the only exception being if the user input is something like cd .... As soon as there are any number of periods other than two, no error is thrown (I've done this without the try/except), and the program remains in the current directory (it prints out wherever it already was, rather than going to the except portion of the statement).

In the grand scheme of things this isn't a big deal, since it's just protecting against a typo, but I'm just wondering what's going on here. Thanks!

役に立ちましたか?

解決

Python isn't doing anything wrong, it seems that windows is just weird about dots.

他のヒント

You could convert more than two dots into a collection of ../ with a regular expression. Something like:

userinput = re.sub('\.\.\.+', lambda x: os.path.join(*['..']*(len(x.group(0))-1)), userinput)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top