如何在运行.py脚本的目录中创建文件



我正试图在运行.py脚本的文件夹中创建一个文件。这是我正在使用的代码。问题是open函数需要/for目录。new_file_path使用\。这导致打开功能失败。我该如何解决这个问题?

import os
dir_path = os.path.dirname(os.path.realpath(__file__))
new_file_path = str(os.path.join(dir_path, 'mynewfile.txt'))
open(new_file_path, "x") 

首先,正如@buran所评论的,不需要使用str,以下就足够了:

new_file_path = os.path.join(dir_path, 'mynewfile.txt')

__file__给出的脚本存在位置和os.getcwd()给出的当前工作目录(通常是调用脚本的位置(之间存在区别。从问题的措辞来看,这并不完全清楚,尽管它们通常是相同的。但以下情况除外:

C:Booboo>python3 testmy_script.py

但在以下情况下:

C:Booboo>python3 my_script.py

但是,如果您试图在当前工作目录中打开一个文件,为什么还要麻烦调用os.getcwd()呢?在不指定任何目录的情况下打开文件,根据定义,应将文件放在当前工作目录中:

import os
with open('mynewfile.txt', "x") as f:
# do something with file f (it will be closed for you automatically when the block terminates

另一个问题可能是打开的文件带有无效标志"x"(如果该文件已经存在(。试试,"w":

with open(new_file_path, "w") as f:
# do something with file f (it will be closed for you automatically when the block terminates

你试过简单的吗

import os
dir_path = os.getcwd()
open(dir_path +'mynewfile.txt', "x")

编辑:很抱歉最后一条消息,它保存了不完整的

您需要使用os.getcwd来获取crrent工作目录

import os
dir_path = os.getcwd()
new_file_path = str(os.path.join(dir_path, 'mynewfile.txt'))
open(new_file_path, "x")

最新更新