【问题标题】:The file is used by another process error followed by unexpected behaviour该文件被另一个进程错误使用,随后出现意外行为
【发布时间】:2018-12-14 14:43:57
【问题描述】:

我正在尝试使用以下代码创建一个 .txt 文件并将其移动到指定文件夹,但我得到 PermissionError: [WinError 32] The process cannot access the file because it is being used by another进程:'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))

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你的代码说

    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 子句时,文件将自动关闭 - 因此您无需担心显式关闭它,即使您想提前 returnraise 异常.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多