Python permission error on windows 10 when moving/renaming file - python

I'm just trying to rename a file or move it to another directory. Either option will work for me. I have the most basic code here that I could find on the internet (first python project here by the way).
import shutil
import os
while True:
for file in os.listdir("C:/Users/lines/OneDrive/Desktop/loc1"):
if file.endswith(".txt"):
shutil.move("C:/Users/lines/OneDrive/Desktop/loc1/" + file, "C:/Users/lines/OneDrive/Desktop/loc2/moved.txt")
# os.rename("C:/Users/lines/OneDrive/Desktop/loc1/" + file, "C:/Users/lines/OneDrive/Desktop/loc2/moved.txt")
But no matter what I try, i ALWAYS get this error in my console when running the file:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/lines/OneDrive/Desktop/loc1/i000130126543220150615123030.txt' -> 'C:/Users/lines/OneDrive/Desktop/loc2/moved.txt'
I truly have no idea how to fix this. Can anyone help?
Edit: both directories are totally empty and only being used for this test purpose. No other text editors have these files open anywhere.

Related

Python Cannot Find File Specified

I am trying to rename a file, but python cannot find the file specified.
I have a file located here:
C:\Users\my_username\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf
I am trying to rename the file to test.pdf
Here is the code I am using:
import os
os.rename(
src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf",
dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf"
)
The error message I am getting is:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf' ->
'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf'
What am I doing wrong?
Edit #1:
The original file was not deleted, it still exists.
It's really strange, when I run it the first time, the file does not get renamed, but when I run it again, it does.
Weird, for some reason it works in Python Shell, but not my Python file.
Edit #2:
I am using Selenium to download the file. When I comment the part of my code out that downloads the file from Selenium, my os.rename code works fine. Weird.
Based off the error, I think you are still leaving one the original name or not changing the right one.
import os
os.rename(
src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf",
dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf"
)
I'm pretty sure you ran the code once, renamed the file, and now it won't run again because you already renamed it.
Careful reading is your friend. Computers don't know or care what you meant:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\my_usernamer\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf'
See the stray r in the path?
Found the solution:
When you download files using Selenium, you need to put in a sleep method for a few seconds and then you can download/move files without a problem.
Put this in your code after downloading the file, before downloading another:
from time import sleep
sleep(10)
pass
You may need to increase the sleep value, but 10 worked for me. The number inside of sleep represents seconds, so sleep(10) means to wait 10 seconds.

Permission Errors When Creating a Directory

In this program I'm checking to see if a directory has been made, if it is then I will delete the directory and make a new one with the same name. If not then the program will carry on to the next step.
import shutil
import os
try:
os.mkdir('Result')
except:
shutil.rmtree('Result')
os.mkdir('Result')
Here I am simply using shutil to remove the directory and then os to add the new one.
>>> os.mkdir('Result')
>>> FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'Result'
However, I don't understand why I am receiving this problem, on some tries the program will work flawlessly with no errors, then on the next it will report back the same error.
The reason as to why I am deleting the folder is because it contains files that I no longer need, new files need to be added and if they are interfered with the program will become corrupt. These files will generally have the same name.
EDIT:
A Fix has been found as I needed to give permission when writing a new directory
os.mkdir('Result', 0o777)

How do i solve "FileNotFoundError: [Errno 2] No such file or directory:" in Python whilst using Visual Studio Code?

I have just started to learn Python and I watched this video tutorial -
https://www.youtube.com/watch?v=rioXu6EBN0s
when I attempted to create my own .hmtl file using the method in the video I got this error -
FileNotFoundError: [Errno 2] No such file or directory:
this is what I have entered into Visual Studio-
my_variable = "<html><body><p>This is a paragraph.</p><p>This is another paragraph.</p></body></html>"
my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html" "w")
my_html_file.write(my_variable)
I have tried changing to
/Users/Liam.Documents/Coding/My Files/Python/My Tests/
/my_html_file.html
but it hasn't worked, any suggestions would be greatly appreciated.
liam
Whenever you need to debug, you need to change the path of the file to open it in debug mode by simply:
Going to the explorer
Right click on the file and click on copy relative path
Put that path in open
Also I saw that you put this in your code:
my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html" "w")
You're missing a coma before the w, it should be like this:
my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html","w")
edit: Lol, now I saw that someone else answer your question by replying, anyway, that should help others too! at least...
The reason for this is that you are missing a comma between the filename and the mode that you are using to open the file. Due to this, the interpreter is trying to read the file, which will lead to an error if the file you are requesting does not exist.

How do I copy all files of one specific type from a folder to another folder in Python

Im trying to copy a numerous amount of .txt files from one folder to another using a Python script. I dont want to copy one single file at a time, and im not even sure exactly how many txt files are present in the folder. I am looking to scan the folder and copy all text files from it to another folder. I have already tried doing this using the shutil and os libraries to no avail. Can someone please help?
import os
import shutil
def start():
dest = "C:/Users/Vibhav/Desktop/Txt"
source = "C:/Users/Vibhav/Desktop/Games"
for file in os.listdir("C:/Users/Vibhav/Desktop/Games"):
if file.endswith(".txt"):
shutil.copy2(dest,source)
This is what I have tried doing, but it doesnt work for me. I keep getting this error
PermissionError: [Errno 13] Permission denied: 'C:/Users/Vibhav/Desktop/Games'
It would really help me if someone could help me out
Main mistake: you're trying to copy the directory, not the file.
Rewriting using glob.glob to get pattern filtering + absolute path sounds the best option:
def start():
dest = "C:/Users/Vibhav/Desktop/Txt"
source = "C:/Users/Vibhav/Desktop/Games"
for file in glob.glob(os.path.join(source,"*.txt")):
shutil.copy2(file,dest)

Python - IOError: [Errno 13] Permission denied:

I'm getting IOError: [Errno 13] Permission denied and I don't know what is wrong wit this code.
I'm trying to read a file given an absolute path (meaning only file.asm),
and a relative path (meaning /.../file.asm), and I want the program to write the file to whatever path is given - if it is absolute, it should write it to the current dir; otherwise, to the path given.
the code:
#call to main function
if __name__ == '__main__':
assem(sys.argv[1])
import sys
def assem(myFile):
from myParser import Parser
import code
from symbolTable import SymbolTable
table=SymbolTable()
# max size of each word
WORD_SIZE = 16
# rom address to save to
rom_addrs = 0
# variable address to save to
var_addrs = 16
# new addition
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
output = open(newFile, 'w') <==== ERROR
the error given:
IOError: [Errno 13] Permission denied: '/Use.hack'
the way I execute the code :
python assembler.py Users/***/Desktop/University/Add.asm
What am I doing wrong here?
Just Close the opened file where you are going to write.
It looks like you're trying to replace the extension with the following code:
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
However, you appear to have the array indexes mixed up. Try the following:
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
Note the use of -4 instead of just 4 in the second line of code. This explains why your program is trying to create /Use.hack, which is the first four characters of your file name (/Use), with .hack appended to it.
You don't have sufficient permissions to write to the root directory. See the leading slash on the filename?
This happened to me when I was using 'shutil.copyfile' instead of 'shutil.copy'. The permissions were messed up.
I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :
chmod 777 University
Maybe You are trying to open folder with open, check it once.
For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.
import os
# create file
#staticmethod
def create_file(path):
if not os.path.exists(path):
os.system('echo # > {}'.format(path))
# append lines to the file
split_text = text_file.split('\n')
for st in split_text:
os.system('echo {} >> {}'.format(st,path))
Check if you are implementing the code inside a could drive like box, dropbox etc. If you copy the files you are trying to implement to a local folder on your machine you should be able to get rid of the error.
For me, this was a permissions issue.
Use the 'Take Ownership' application on that specific folder.
However, this sometimes seems to work only temporarily and is not a permanent solution.
FYI I had this permission error because the file that it was trying to create was already open/used by another program (was created last time the script was run, I had opened it with excel, and then got a permission error when it was trying to recreate it)
leaving this here in case someone else finds it useful, it is not the real solution to the question asked
I got this error because the directory didn't exist yet.
Solution: create the directory
import os
if not os.path.exists(directory):
os.makedirs(directory)

Categories

Resources