open() function python default directory

后端 未结 7 1437
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 00:23

I\'m new and I have no idea where the default directory for the open() function is.

For example open(\'whereisthisdirectory.txt\',\'r\')

相关标签:
7条回答
  • 2021-01-05 00:51

    create the .txt file in the directory where u have kept .py file(CWD) and run the .py file.

    0 讨论(0)
  • 2021-01-05 00:53

    The open() function for file always creates files in the current working directory. The best way to find out your current working directory is to find three lines of small code:

    import os
    current_working_directory = os.getcwd()
    print(current_working_directory)
    

    Run this above code and you will get your current working directory where open() function creates a new file. Good Luck!

    0 讨论(0)
  • 2021-01-05 00:54

    The default location is the CWD (Current Working Directory), so if you have your Python script in c:\directory and run it from there, if you call open() it will attempt to open the file specified in that location.

    0 讨论(0)
  • 2021-01-05 00:57

    The answer is not python-specific. As with programs written in any other language, the default directory is whatever your operating system considers the current working directory. If you start your program from a command prompt window, that is whatever directory you were in when you ran the program. If you start it from a Windows menu or desktop icon, that directory is usually defined alongside the program's path when creating the icon, or else falls back to some directory that Windows uses in the absence of that information.

    In any case, your program can query the current working directory by calling os.getcwd().

    0 讨论(0)
  • 2021-01-05 01:02

    If you working on Windows OS first type

    import os
    

    then type

    os.getcwd()
    

    and it should print the current working directory.

    0 讨论(0)
  • 2021-01-05 01:09

    os.getcwd()

    Shows the current working directory, that's what open uses for for relative paths. You can change it with os.chdir.

    0 讨论(0)
提交回复
热议问题