猿问

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

我正在 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 运行程序,而不是从项目根目录运行程序?


暮色呼如
浏览 164回答 3
3回答
随时随地看视频慕课网APP

相关分类

Python
我要回答