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

时间:2020-03-15 11:43:01

标签: python

我试图在运行.py脚本的文件夹中创建一个文件。这是我正在使用的代码。问题在于open函数要求/用于目录。 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") 

3 个答案:

答案 0 :(得分:2)

首先,如@buran所述,无需使用str,即可满足以下要求:

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

__file__给出的脚本存在的位置与由os.getcwd()给出的当前工作目录(通常是调用脚本的位置)之间存在区别。从问题措词中并不能完全弄清是谁打算的,尽管它们通常是相同的。但在以下情况下则不会:

C:\Booboo>python3 test\my_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

答案 1 :(得分:0)

您需要使用os.getcwd来获取最新的工作目录

import os

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

答案 2 :(得分:-1)

您是否尝试过

import os

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

编辑:对不起,最后一条消息,它保存不完整