为什么python假设我的路径是项目根目录,即两个目录级别?

时间:2019-02-01 00:49:38

标签: python python-3.x visual-studio-code

我正在Lynda上学习一些python教程。本教程中的脚本具有与脚本相同的目录中创建文件的功能,就像人们期望的那样。

但是,无论出于何种原因,我的安装过程都是在项目根目录或两个目录中创建文件并希望读取文件(使用路径对象)。

我正在运行的脚本为C:\Users\user\Development\Ex_Files_Learning_Python\Exercise Files\Ch4

脚本如下:

import os
from os import path
import datetime
from datetime import date, time, timedelta
import time


def main():
  # Print the name of the OS
  print(os.name)

  # Check for item existence and type
  print("Item exists: " + str(path.exists("textfile.txt")))
  print("Item is a file: " + str(path.isfile("textfile.txt")))
  print("Item is a directory: " + str(path.isdir("textfile.txt")))
  # Work with file paths
  print("Item path" + str(path.realpath("textfile.txt")))
  print("Item path and name: " + str(path.split(path.realpath("textfile.txt"))))

  # Get the modification time


  # Calculate how long ago the item was modified



if __name__ == "__main__":
  main()

其输出为

nt
Item exists: False
Item is a file: False
Item is a directory: False
Item pathC:\Users\user\Development\Ex_Files_Learning_Python\textfile.txt
Item path and name: ('C:\\Users\\user\\Development\\Ex_Files_Learning_Python', 'textfile.txt')

因此,如您所见,它假定其路径是项目根目录,即两个目录。在上一个练习中,我创建文件时遇到了同样的问题。当我在文件对象上使用open()时,它在项目根目录的两个目录中创建了文件。

任何指针都值得赞赏。

更新:我已经确定正在发生这种情况,因为我正在使用VSCode终端。如何指示VSCode终端从我正在编辑和调试的文件的cwd中而不是从项目根目录运行程序?

记录下来,这是调试器的launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": ".",
                    "remoteRoot": "."
                }
            ]
        },
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "enter-your-module-name-here",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "console": "integratedTerminal",
            "args": [
                "runserver",
                "--noreload",
                "--nothreading"
            ],
            "django": true
        },
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
        {
            "name": "Python: Current File (External Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "externalTerminal"
        }
    ]
}

4 个答案:

答案 0 :(得分:3)

根据https://code.visualstudio.com/docs/python/settings-reference

  

python.terminal.executeInFileDir
  错误
  指示是否运行在文件的目录中的文件,而不是当前文件夹的。

因此大概将python.terminal.executeInFileDir设置为true

答案 1 :(得分:1)

如果你从终端运行脚本,你可能运行:

python "Exercise Files\Ch4\my_script.py"

或类似的东西。

相反,请先更改文件夹,然后在终端上运行它:

cd "Exercise Files\Ch4"
python my_script.py

或者,为避免所有这些手动目录切换,请在脚本中显式更改工作目录。

答案 2 :(得分:1)

这是我的错,因为我没有明确说明我试图在VSCode中修改调试器终端。 @Adam Smith的答案适合处理标准终端的大多数情况。

但是,如果您尝试从调试器运行文件,则答案是将“ cwd”设置为空字符串,即launch.json(当前调试器配置)中的“”。

https://code.visualstudio.com/docs/python/debugging#_cwd

答案 3 :(得分:0)

您需要使用的是__file__内置变量,Python将其与当前Python文件名相关联。

请参阅what does the __file__ variable mean/do?

如果您使用的是Python 3,这应该可以工作。

pathlib.Path在Python 3上,用于操纵文件路径。

  from pathlib import Path                            
  myfilepath = Path(Path(__file__).resolve()).parent / "textfile.txt"
                    ^            ^
                    find the currrent script location
                                             ^ get its parent directory
                                                        ^ add your file name

这是脚本

import os
from os import path
import datetime
from datetime import date, time, timedelta
import time


def main():
  # Print the name of the OS
  print(os.name)

  from pathlib import Path
  myfilepath = Path(Path(__file__).resolve()).parent / "textfile.txt"

  # Check for item existence and type
  print("Item exists: " + str(path.exists(myfilepath)))
  print("Item is a file: " + str(path.isfile(myfilepath)))
  print("Item is a directory: " + str(path.isdir(myfilepath)))
  # Work with file paths
  print("Item path" + str(path.realpath(myfilepath)))
  print("Item path and name: " + str(path.split(path.realpath(myfilepath))))

  # Get the modification time


  # Calculate how long ago the item was modified

main()

输出:

posix
Item exists: True
Item is a file: True
Item is a directory: False
Item path/Users/jluc/kds2/wk/explore/textfile.txt
Item path and name: ('/Users/jluc/kds2/wk/explore', 'textfile.txt')

如果您使用的是Python 2,则可以使用以下方法获得相同的结果:

({os.path.join("foo", "bar")在Windows上将返回foo\bar,在Linux / macOs上将返回foo/bar

#from pathlib import Path
myfilepath = os.path.join(os.path.dirname(__file__), "textfile.txt")
                          ^ get parent directory
                                                     ^ append your filename