Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 该文件被另一个进程错误使用,随后出现意外行为_Python_Python 3.x - Fatal编程技术网

Python 该文件被另一个进程错误使用,随后出现意外行为

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),

我正试图创建一个.txt文件,并使用下面的代码将其移动到指定的文件夹,但我获得了权限错误:[WinError 32]该进程无法访问该文件,因为它正被另一个进程使用:“C:\Users\Emre\Desktop\testbot\asdf\testuser.txt”

此错误后,脚本将在脚本正在运行的目录和我希望shutil将txt文件移动到的目录中创建txt文件。我该怎么办?提前谢谢

    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
子句时,该文件将自动关闭,因此您不必担心显式关闭它,即使您希望
尽早返回
引发
异常