Python 该文件被另一个进程错误使用,随后出现意外行为
我正试图创建一个.txt文件,并使用下面的代码将其移动到指定的文件夹,但我获得了权限错误:[WinError 32]该进程无法访问该文件,因为它正被另一个进程使用:“C:\Users\Emre\Desktop\testbot\asdf\testuser.txt” 此错误后,脚本将在脚本正在运行的目录和我希望shutil将txt文件移动到的目录中创建txt文件。我该怎么办?提前谢谢Python 该文件被另一个进程错误使用,随后出现意外行为,python,python-3.x,Python,Python 3.x,我正试图创建一个.txt文件,并使用下面的代码将其移动到指定的文件夹,但我获得了权限错误:[WinError 32]该进程无法访问该文件,因为它正被另一个进程使用:“C:\Users\Emre\Desktop\testbot\asdf\testuser.txt” 此错误后,脚本将在脚本正在运行的目录和我希望shutil将txt文件移动到的目录中创建txt文件。我该怎么办?提前谢谢 import shutil file = open("{}.txt".format(source),
import shutil
file = open("{}.txt".format(source), "w")
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
file.close
shutil.move("C:\\Users\\Emre\\Desktop\\testbot\\asdf\\{}.txt".format(source), "C:\\Users\\Emre\\Desktop\\testbot\\asdf\\users")
self.bot.say(channel, "You have been successfully registered, {}!".format(source))
你的密码是
file.close
应该说什么时候
file.close()
因为您只是“提到”了close
方法,而不是实际调用它,所以文件没有关闭。因为它仍然打开,你将无法移动它
请注意,打开文件的最佳做法是使用上下文管理器:
with open("{}.txt".format(source), "w") as file:
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
shutil.move( ...
然后,当您出于任何原因退出with
子句时,该文件将自动关闭,因此您不必担心显式关闭它,即使您希望尽早返回
或引发
异常