我正在 Lynda 上做一些 Python 学习教程。正如人们所期望的那样,本教程使用脚本在与脚本相同的目录中创建文件。但是,无论出于何种原因,我的安装正在创建文件并希望在项目根目录或两个目录中读取文件(使用路径对象)。我正在运行的脚本是 C:\Users\user\Development\Ex_Files_Learning_Python\Exercise Files\Ch4该脚本如下所示:import osfrom os import pathimport datetimefrom datetime import date, time, timedeltaimport timedef 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 modifiedif __name__ == "__main__": main()它的输出是ntItem exists: FalseItem is a file: FalseItem is a directory: FalseItem pathC:\Users\user\Development\Ex_Files_Learning_Python\textfile.txtItem path and name: ('C:\\Users\\user\\Development\\Ex_Files_Learning_Python', 'textfile.txt')如您所见,它假定其路径是项目根目录,向上两个目录。我在之前的练习中遇到了同样的问题,创建了一个文件。当我在文件对象上使用 open() 时,它在项目的根目录中创建了两个目录的文件。任何指针表示赞赏。更新:我已经确定这是因为我正在使用 VSCode 终端。如何指示 VSCode 终端从我正在编辑和调试的文件的 cwd 运行程序,而不是从项目根目录运行程序?
添加回答
举报
0/150
提交
取消