为什么python open()函数未在与主机文件相同的文件夹内创建.txt文件?

时间:2018-10-29 09:08:22

标签: python

我是一个初学者,正在Visual Studio中处理python代码。我已使用以下python文件const array = [{location:'Table 27'}, {location:'Table 2'}, {location: 'Unassigned'}, {location: 'Table 11'}]; const result = [...array].sort(({ location: a }, { location: b }) => { if(a === 'Unassigned') return 1; if(b === 'Unassigned') return -1; return a.localeCompare(b, undefined, {numeric: true}); }); console.log(result);创建了一个目录Test_Folder

Test.py

正在new_file = open('README.txt','w') new_file.close() 之外创建README.txtTest.py的结果文件:

Test_Folder

为什么会这样?以及如何在同一目录中创建文本文件?

1 个答案:

答案 0 :(得分:2)

该文件是在“当前工作目录”(cwd)中创建的,该目录是您运行命令python my_script.py的文件夹。

如果运行此命令:

cd /path/to/Test_folder
python Test.py

该文件将在/path/to/Test_folder中创建。

如果您运行

cd /path/to
python Test_folder/Test.py

该文件将在/path/to中创建。

如果要查看脚本中的具体“当前工作目录”是什么,

>>> import os
>>> print(os.getcwd())
'/path/to/your_current_working_directory'

由于使用VSCode运行脚本,因此可以从项目文件夹中的launch.json文件配置“ cwd”。有关更多信息,请参见this Q/A

{
    // [...]
    "cwd": "<Path to the directory>"
}