[英]How do I open a file in a specific directory?
This is my code:这是我的代码:
import os
...
savepath = "/home/myname/Documents/programfolder/vanities/"
#ctx.author.id is from the discord.py module, not relevant to question.
userFile = os.path.join(savepath, str(ctx.author.id) + ".txt")
...
try:
vanity = open(userFile, "r")
vanity = vanity.read()
server = get_guild(myserverid)
vanityrole = server.get_role(vanity)
vanityrole = role.edit(name = str(rolename), colour = int(hexcolour))
except FileNotFoundError:
vanity = open(userFile, "w")
vanityrole = role_create(name = str(rolename), colour = int(hexcolour))
vanity = vanity.write(str(vanityrole.id))
pass
When I run this, I receive an error当我运行这个时,我收到一个错误
Ignoring exception in command vanity:
Traceback (most recent call last):
File "./bot.py", line 27, in vanity
vanity = open(userFile, "r")
FileNotFoundError: [Errno 2] No such file or directory: '/home/myname/Documents/programfolder/vanities/myid.txt'
Why does the try: except FileNotFoundError: not work?为什么 try: except FileNotFoundError: 不起作用? I tried it with except IOError and OSError and neither worked.
我尝试过除了 IOError 和 OSError 之外,但都没有奏效。 The error also occurs with open(userFile, "w").
open(userFile, "w") 也会出现该错误。 For reference, my program runs in /home/myname/Documents/programfolder/
作为参考,我的程序运行在 /home/myname/Documents/programfolder/
Check if savepath
exists.检查保存
savepath
存在。
The with
clause takes care of closing resources, in most cases.在大多数情况下,
with
子句负责关闭资源。 You can wrap something like this in a try/catch, or check first if the directory doesn't exist (first link above) and then create if needed.您可以在 try/catch 中包装类似的内容,或者首先检查目录是否不存在(上面的第一个链接),然后根据需要创建。
# handle directory existence first, here
...
with open(userFile, 'a+') as fp:
fp.seek(0)
contents = fp.read()
# handle contents if found, here
if not contents:
newContents = ...
fp.write(newContents)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.