Reputation: 325
I'm trying to create a .txt file and move it to a specified folder using the code below, but I get PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\Emre\Desktop\testbot\asdf\testuser.txt'
this error which is followed by the script creating a txt file in both the directory the script is running and the directory I wanted shutil to move the txt file to. What should I do? Thanks in advance.
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))
Upvotes: 2
Views: 541
Reputation: 15349
Your code says
file.close
when it should say
file.close()
Since you are just "mentioning" the close
method rather than actually calling it, the file is not getting closed. And because it is still open, you will not be able to move it.
Note that the best practice for opening files is to use a context manager:
with open("{}.txt".format(source), "w") as file:
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
shutil.move( ...
Then the file will get automatically closed when you exit the with
clause for any reason—so you don't need to worry about closing it explicitly, even if you want to return
early or raise
an exception.
Upvotes: 3