How to know/change current directory in Python shell?

后端 未结 7 1962
无人及你
无人及你 2020-11-27 09:27

I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules

相关标签:
7条回答
  • 2020-11-27 09:48

    You can use the os module.

    >>> import os
    >>> os.getcwd()
    '/home/user'
    >>> os.chdir("/tmp/")
    >>> os.getcwd()
    '/tmp'
    

    But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

    export PYTHONPATH=/path/to/my/library:$PYTHONPATH
    

    Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

    edit

    Under Windows:

    set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
    

    (taken from http://docs.python.org/using/windows.html)

    edit 2

    ... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

    http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

    0 讨论(0)
  • 2020-11-27 09:53

    If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory

    0 讨论(0)
  • 2020-11-27 09:58

    You can try this:

    import os
    
    current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
    print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
    new_dir = os.chdir('..\\..\\..\\')                         
    print(new_dir)                                             # prints "D:\abc\def\ghi"
    
    
    
    0 讨论(0)
  • 2020-11-27 09:59
    >>> import os
    >>> os.system('cd c:\mydir')
    

    In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

    0 讨论(0)
  • 2020-11-27 10:02

    The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

    # Import the os package
    import os
    
    # Confirm the current working directory 
    os.getcwd()
    
    # Use '\\' while changing the directory 
    os.chdir("C:\\user\\foldername")
    
    0 讨论(0)
  • 2020-11-27 10:03

    you want

    import os
    os.getcwd()
    os.chdir('..')
    
    0 讨论(0)
提交回复
热议问题