如何在特定目录中制作文件python

How to make a file in a specific directory python

我想在特定的“帐户”目录中创建一个文件,但我一直收到错误消息:

FileNotFoundError: [Errno 2] No such file or directory: '/accounts/Jason Silla.txt'

这是我的代码,所以如果有人能解释发生了什么。我在 Mac.

上使用最新版本的 python
filePath = join("/accounts", username + ".txt")
newuser = open(filePath, "w")
newuser.write(username + "\n" + password)

我也看过其他关于此的帖子,但如您所见,它对我不起作用。我确实从 os.path 导入连接,所以这不是问题。

您可能不想将您的目录称为 "/accounts",而是将其称为 "accounts"。当您在文件名的开头使用前导斜杠 / 时,您指的是相对于整个文件存储树根目录的目录。如果没有前导斜杠,那么您指的是相对于您的脚本所在的当前本地目录的目录 运行.

仔细检查您的 accounts 目录是否存在,如果不存在,请创建它。

try:
    # remove leading '/' if you want to work in the current directory
    os.makedirs("accounts")  
except FileExistsError:
    # directory already exists
    newuser = open(filePath, "w") 
    # etc etc ...

检查在你运行这个python文件所在的同一目录下是否有'accounts'目录,如果没有就创建i