PyCharm current working directory

前端 未结 8 1368

Recently, I\'m unable to use relative paths in my code while using PyCharm. For instance, a simple open(\'test.txt\', \'r\') will not work - whereupon I am sure

相关标签:
8条回答
  • 2020-11-28 08:28

    Sometimes it is different. I solved my problem by clicking "Run" at the Pycharm's toolbar and then "Edit Configurations..." and I change my Interpreter to another actual one. Just changing it in the settings does not help, but this opperation already does ;)

    0 讨论(0)
  • 2020-11-28 08:31

    Current version 2019.2 somehow ignores "source root" from the "project structure". Here's how to actually enforce it:

    Run -> Edit Configurations -> Python -> "Edit Templates" -> fill out "Working Directory"

    0 讨论(0)
  • 2020-11-28 08:34

    __file__ refers to file path. So you can use the following to refer file in the same directory:

    import os
    
    dirpath = os.path.dirname(__file__)
    filepath = os.path.join(dirpath, 'test.txt')
    open(filepath, 'r')
    
    0 讨论(0)
  • 2020-11-28 08:34

    A little clarification for mac users. In mac, what @andere said above is correct for setting working directory. However, if your code is in a different folder, say working_dir/src/ (like classic java/scala file structure) in that case you still need to set your Sources Root. In mac's PyCharm this can be done by right clicking on the src/ folder > Mark Directory as > Sources Root. Helped me with lot of similar import issues. Hope this helps someone.

    0 讨论(0)
  • 2020-11-28 08:41

    I too had the same issue few minutes ago...but,with the latest version of PyCharm it is resolved by simply using the relative path of that file.. For instance, a simple f = open('test', 'r') will work.

    0 讨论(0)
  • 2020-11-28 08:43

    In PyCharm, click on "run/edit configurations..."

    Then find your script file in the "Python" dropdown menu. Check the "Working Directory" entry and change it if necessary.

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