IOError: [Errno 13] Permission denied: Bulk renaming script - python

This is one of my first python scripts designed to go into a directory and rename all the files of a certain extension to the same thing. For instance, go into a music directory and change the name of all the album artwork files to something like folder.jpg so that they're easily recognized and displayed by music playing software like foobar2000.
I'm currently getting the error in the title. I've tried:
os.chmod(pathname, 0777)
and
os.chmod(pathname, stat.S_IWOTH)
to allow other entities to edit the directory I'm looking at, but the error remains. I'm not too familiar with Windows's permissions system or with Python so this is mystifying me. Any idea where I'm going wrong?
#Changes file names in every subdirectory of the target directory
import os
import sys
import shutil
#Get target path
pathname = raw_input('Enter path for music directory (ex. C:\\Music): ')
try:
os.chdir(pathname)
except:
print('Failed. Invalid directory?')
sys.exit()
#Get variables for renaming
fn = raw_input('Enter desired file name for all converted files: ')
ft = raw_input('Enter the file extension you want the program to look for (ex. .jpg): ')
outname = fn + ft
#Create path tree
for path, subdirs, files in os.walk (pathname):
#Search tree for files with defined extention
for name in files:
if name.lower().endswith(ft):
#Rename the files
src = os.path.join(path, name)
print (src)
dst = os.path.join(path, outname)
print dst
shutil.move(src, dst)
print('Complete')
A second more benign issue is that when I use a print statement to check on what files are being edited, it seems that before the first .jpg is attempted, the program processes and renamed a file called d:\test\folder.jpg which doesn't exist. This seems to succeed and the program fails in the last loop the second time through, when an existing file is processed. The program runs like this:
>>> ================================ RESTART ================================
>>>
Enter path for music directory (ex. C:\Music): d:\test
Enter desired file name for all converted files: folder
Enter the file extension you want the program to look for (ex. .jpg): .jpg
d:\test\folder.jpg
d:\test\folder.jpg
d:\test\Anathema\Alternative 4\AA.jpg
d:\test\Anathema\Alternative 4\folder.jpg
Traceback (most recent call last):
File "D:\Documents\Programming\Python scripts\Actually useful\bulk_filename_changer.py", line 29, in <module>
shutil.move(src, dst)
File "C:\Python27\lib\shutil.py", line 301, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'd:\\test\\Anathema\\Alternative 4\\folder.jpg'
>>>
The glitch seems to be benign because it doesn't cause an error, but it might be related to an error I have in the code that leads to the IOError I get when the first "real" file is processed. Beats me...

I am assuming that d: is not a CD drive or something not writable. If so then have you checked the properties of your files? Are any of them read only? There would also need to be more than one of the file type in the folder to cause this, I believe.

Related

Using shutil.copytree to copy folder that already exists

I have the codes to copy folders with names that match the IDs on a csv list, it has been working well copying all the folders until it finds a folder with a name that already exists in the destination folder. I believe the issue comes from the following section of the codes,because I thought the if function should let shutil.copytree skip if it finds a foldername matches exactly with a folder in the destination folder.
save_path = r""
for i, r in df.iterrows():
date = r["Date"]
ID = r["ID"]
survey_paths = findSurveys(path = SourcePath, survey_id = ID)
for path in survey_paths:
temp = path.split("\\")
save_date = temp[-2]
save_id = temp[-1]
#compare if the path of previously saved survey equals the new one
if save_path != rf"{DstPath}\{save_date}\{save_id}":
shutil.copytree(path,rf"{DstPath}\{save_date}\{save_id}")
save_path = rf'{DstPath}\{save_date}\{save_id}'
print(save_path.split("\\")[-1]+ " ("+ save_path.split("\\")[-2]+ ")"" copied!")
The following is the error I got:
Traceback (most recent call last):
File "Z:\Python\DCPA\FolderCopy\FolderCopy.py", line 34, in <module>
shutil.copytree(path,rf"{DstPath}\{save_date}\{save_id}")
File "Z:\Apps\Anaconda3\lib\shutil.py", line 565, in copytree
return _copytree(entries=entries, src=src, dst=dst, symlinks=symlinks,
File "Z:\Apps\Anaconda3\lib\shutil.py", line 466, in _copytree
os.makedirs(dst, exist_ok=dirs_exist_ok)
File "Z:\Apps\Anaconda3\lib\os.py", line 225, in makedirs
mkdir(name, mode)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'Y:\\P43_NEW\\2022-02-21\\112_1'
You're potentially only checking against the last saved path!
I'd use the os package to check and see if the directory exists before attempting a save.
Here's a quick snippet of what occurs to me (its untested).
import os
if not os.path.isdir(r"path/to/folder"):
save_path = (r"path/to/folder")
Here's a quick link to get you started on a fix also, if you need to hunt down more solutions when it comes to file stuff. Another option is to append the current time to the end of your folders so that every folder you create is unique every time.
from datetime import datetime
# earlier creation of the save path
save_path = save_path + datetime.now().strftime("%H%M%S"),
See Python: Check if a File or Directory Exists.
You could use try, except insted If.
try:
shutil.copytree(path,rf"{DstPath}\{save_date}\{save_id}")
save_path = rf'{DstPath}\{save_date}\{save_id}'
print(save_path.split("\\")[-1]+ " ("+ save_path.split("\\")[-2]+ ")"" copied!")
except FileExistsError:
pass

How to Fix "Python permission denied error" [duplicate]

I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
What's the problem?
Read the docs:
shutil.copyfile(src, dst)
Copy the contents (no metadata) of the file named src to a file
named dst. dst must be the complete target file name; look at copy()
for a copy that accepts a target directory path.
use
shutil.copy instead of shutil.copyfile
example:
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
Use shutil.copy2 instead of shutil.copyfile
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
I solved this problem, you should be the complete target file name for destination
destination = pathdirectory + filename.*
I use this code fir copy wav file with shutil :
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
First of all, make sure that your files aren't locked by Windows, some applications, like MS Office, locks the oppened files.
I got erro 13 when i was is trying to rename a long file list in a directory, but Python was trying to rename some folders that was at the same path of my files. So, if you are not using shutil library, check if it is a directory or file!
import os
path="abc.txt"
if os.path.isfile(path):
#do yor copy here
print("\nIt is a normal file")
Or
if os.path.isdir(path):
print("It is a directory!")
else:
#do yor copy here
print("It is a file!")
Visual Studio 2019
Solution : Administrator provided full Access to this folder "C:\ProgramData\Docker"
it is working.
ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'
[ERROR]: Failed to run 'iotedgehubdev start -d "C:\Users\radhe.sah\source\repos\testing\AzureIotEdgeApp1\config\deployment.windows-amd64.json" -v' with error: WARNING! Using --password via the CLI is insecure. Use --password-stdin.
ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'
use
> from shutil import copyfile
>
> copyfile(src, dst)
for src and dst use:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
This works for me:
import os
import shutil
import random
dir = r'E:/up/2000_img'
output_dir = r'E:/train_test_split/out_dir'
files = [file for file in os.listdir(dir) if os.path.isfile(os.path.join(dir, file))]
if len(files) < 200:
# for file in files:
# shutil.copyfile(os.path.join(dir, file), dst)
pass
else:
# Amount of random files you'd like to select
random_amount = 10
for x in range(random_amount):
if len(files) == 0:
break
else:
file = random.choice(files)
shutil.copyfile(os.path.join(dir, file), os.path.join(output_dir, file))
Make sure you aren't in (locked) any of the the files you're trying to use shutil.copy in.
This should assist in solving your problem
I avoid this error by doing this:
Import lib 'pdb' and insert 'pdb.set_trace()' before 'shutil.copyfile', it would just like this:
import pdb
...
print(dst)
pdb.set_trace()
shutil.copyfile(src,dst)
run the python file in a terminal, it will execute to the line 'pdb.set_trace()', and now the 'dst' file will print out.
copy the 'src' file by myself, and substitute and remove the 'dst' file which has been created by the above code.
Then input 'c' and click the 'Enter' key in the terminal to execute the following code.
well the questionis old, for new viewer of Python 3.6
use
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
instead of
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
r argument is passed for reading file not for copying

Transfering files from one directory to another via python

I'm trying to move multiple files from one directory to another.
The function I'm trying to make should move files if they begin with a value in sample_list. My issue is that there are multiple files which begins with a value in sample_list, this seems to be causing issues for shutil.
import shutil
import os
source = './train/'
dest1 = './test/'
files = [
'195_reg_6762_1540.npz',
'1369_reg_7652_-2532.npz',
'195_reg_1947_-484.npz',
'1336_reg_6209_1217.npz',
'1198_reg_3784_-934.npz',
'12_reg_3992_-10.npz',
'1369_reg_3214_-91.npz']
test_samples = [195, 1493, 409, 339, 12, 1336]
#Move files which begin with values in test_samples [edited orig post to fix typo]
for f in files:
for i in test_samples:
if (f.startswith(str(i))):
shutil.move(source+f, dest1)
Raises the error:
File "/home/usr/anaconda3/lib/python3.7/shutil.py", line 564, in move
raise Error("Destination path '%s' already exists" % real_dst)
Error: Destination path '/home/usr/Documents/project/data/test/195_reg_1947_-484.npz' already exists
It always fails if there is more than one file with a value in test samples to move.
What would be the correct way to move files which begin with values in test_samples from source directory to target directory.
This occurs when you've already successfully run the script (or parts of it once). Once the file exists in the destination directory, shutil throws an exception if you try to replace it.
See this modification that checks if the file already exists in the destination directory and, if so, deletes it and moves it back from the origin directory (note that the file must exist again in the origin directory). [Do you mean to copy instead of move?]
for f in files:
for i in test_samples:
if (f.startswith(str(i))):
if not os.path.exists(dest1+f):
shutil.move(source+f, dest1)
else:
os.remove(dest1+f)
shutil.move(source+f,dest1)

Compress photo and put to another directory with tinify and python

I'm slowly starting to study about python and wanted to write simple script which use tinify api, takes photos from unoptimalized directiory, compress it and put to optimalized directory. So far works partly, I mean weirdly I need to keep photos in main directory and unoptimalized one. If I dont have another copy in one of these directories, I have error. another thing is that after I launch script, only first photo is compressed and put inside optimalized directory, and then error appears.
So far I'm experimenting on two photos: lew.jpg and kot.jpg
My directory structure is like this:
Main root directory with script, and two other directories inside (optimalized and unoptimalized)
def optimalizeImages():
for fname in os.listdir('./unoptimalized'):
if fname.endswith(".jpg"):
print(fname)
source = tinify.from_file(fname)
print("processing", fname)
os.chdir("./optimalized")
source.to_file("optimalized-" + fname)
print("changed", fname)
optimalizeImages()
Error after processing first image:
Traceback (most recent call last):
File "python.py", line 20, in <module>
optimalizeImages()
File "python.py", line 11, in optimalizeImages
source = tinify.from_file(fname)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/__init__.py", line 79, in from_file
return Source.from_file(path)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/source.py", line 13, in from_file
with open(path, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'kot.jpg'
and if i keep photos only in root directory, no error but also no any action, if i keep them only in unoptimalized i get same error:
Traceback (most recent call last):
File "python.py", line 20, in <module>
optimalizeImages()
File "python.py", line 11, in optimalizeImages
source = tinify.from_file(fname)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/__init__.py", line 79, in from_file
return Source.from_file(path)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/source.py", line 13, in from_file
with open(path, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'lew.jpg'
There are two issues here, both because you are using relative filenames. os.listdir() gives you those relative filenames, without a path. Instead of ./unoptimalized/kot.jpg, you get just kot.jpg.
So when you try to load the image:
source = tinify.from_file(fname)
you tell the library to load image.jpg without any context other than the current working directory. And that's not the right directory, not if os.listdir('./unoptimalized') worked to list all image files; that indicates that the current working directory is in the parent directory of both unoptimalized and optimalized.
You solved that by putting an image file with the same name in the parent directory, but that's not quite the right way to solve this. More on this below.
The next issue is that you change the working directory:
os.chdir("./optimalized")
You do this for the first image, so now the current working directory has changed to optimalized. When you then loop back up for the next file, you are now in the wrong location altogether to read the next file. Now lew.jpg, which might exist in ./unoptimalized or the parent directory, can't be found because it is not there in ./optimalized.
The solution is to add on the directory name. You can do so with os.path.join(), and not changing directories:
def optimalizeImages():
input_dir = './unoptimalized'
output_dir = './optimalized'
for fname in os.listdir(input_dir):
if fname.endswith(".jpg"):
print(fname)
source = tinify.from_file(os.path.join(input_dir, fname))
print("processing", fname)
source.to_file(os.path.join(output_dir, "optimalized-" + fname))
print("changed", fname)
Note that this still depends heavily on the current working directory being correct, but at least it is now stable and stays at the parent directory of both optimalized and unoptimalized. You may want to change that to using absolute paths.
And a side note on language: In English, the correct spelling of the two terms is optimized and unoptimized. I didn't correct those in my answer to keep the focus on what is going wrong.

Python Permission Error when reading

import os
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(os.path.dirname(file+'.txt'),"r")
with this code I am getting the error:
Traceback (most recent call last):
File "C:\Users\Nick L\Desktop\Programming\PythonProgramming\RarCracker.py", line 7, in <module>
passwordList = open(os.path.dirname(file+'.txt'),"r")
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nick L\\Desktop'
This is weird because I have full permission to this file as I can edit it and do whatever I want, and I am only trying to read it. Every other question I read on stackoverflow was regarding writing to a file and getting a permissions error.
You're trying to open a directory, not a file, because of the call to dirname on this line:
passwordList = open(os.path.dirname(file+'.txt'),"r")
To open the file instead of the directory containing it, you want something like:
passwordList = open(file + '.txt', 'r')
Or better yet, use the with construct to guarantee that the file is closed after you're done with it.
with open(file + '.txt', 'r') as passwordList:
# Use passwordList here.
...
# passwordList has now been closed for you.
On Linux, trying to open a directory raises an IsADirectoryError in Python 3.5, and an IOError in Python 3.1:
IsADirectoryError: [Errno 21] Is a directory: '/home/kjc/'
I don't have a Windows box to test this on, but according to Daoctor's comment, at least one version of Windows raises a PermissionError when you try to open a directory.
PS: I think you should either trust the user to enter the whole directory-and-file name him- or herself --- without you appending the '.txt' to it --- or you should ask for just the directory, and then append a default filename to it (like os.path.join(directory, 'passwords.txt')).
Either way, asking for a "directory" and then storing it in a variable named file is guaranteed to be confusing, so pick one or the other.
os.path.dirname() will return the Directory in which the file is present not the file path. For example if file.txt is in path= 'C:/Users/Desktop/file.txt' then os.path.dirname(path)wil return 'C:/Users/Desktop' as output, while the open() function expects a file path.
You can change the current working directory to file location and open the file directly.
os.chdir(<File Directory>)
open(<filename>,'r')
or
open(os.path.join(<fileDirectory>,<fileName>),'r')

Categories