Permission denied on shutil.move on image files - python

I am trying to move some files around. I can move any extension type except .png, .jpg, or .gif. When I try to move those types of files I get "IOError: [Errno 13] Permission denied" even though I am the admin. Code below
import os, glob, shutil
dir = r'C:\\Users\\jcan4\\Desktop\\testmove\\*'
print(dir)
files = glob.glob(dir)
files.sort(key=os.path.getmtime)
for i, file in enumerate(files, start=1):
print(file)
oldext = os.path.splitext(file)[1]
shutil.move(file, 'Attachment-%s' % (i) + oldext)

First things first, you're double escaping your dir variable:
print(r'C:\\Users\\jcan4\\Desktop\\testmove\\*')
# Yields 'C:\\\\Users\\\\jcan4\\\\Desktop\\\\testmove\\\\*' !!
# What you really meant was either one of the following:
dir_harderToRead = 'C:\\Users\\jcan4\\Desktop\\testmove\\*'
dir_easyToRead = r'C:\Users\jcan4\Desktop\testmove\*'
If you are still experiencing the error, it's because you are not giving the python script permissions to move the file. There are a couple ways to get around this:
Windows
(This applies to the asked question)
Open command prompt (I see your file path and am assuming you're on windows) with administrative rights. (see here)
Change ownership of the images to you. (see here for windows 10 or here for windows 7)
Linux (MacOS)
(This applies to people on Linux that may have the same problem)
Run the python script with root privileges:
# At command line
sudo python your_script_name.py
Change ownership of file to yourself:
# At command line
# Changes ownership of entire directory (CAREFUL):
chmod 755 /absolute/path/to/dir
chmod 755 relative/path/to/dir
# Or you can change file by file:
chmod 755 /absolute/path/to/file
chmod 755 relative/path/to/file
For more info, I used this site on permissions. (If someone has a numerical value than 755 for chmod please say so.)

Related

ERROR PermissionError: [Errno 13] Permission denied: '/var/task/main.py'

I have a python Lambda that returns this error. This function only read a json event and parse some fields. Stop. I can't paste here the lambda code. This lambda has always worked and with no changes stopped!!!
Lambda code is taken from a BitBucket repository.
    
Have you by any chance updated the .zip package for lambda? The error might have something to do with the following:
The zip archive preserves file permissions, so if you have a 644
permissions file, deflate it and inflate it back up, you get 644
permissions for that file.
Try setting the expected permissions before deflation, in Lambda's case, 755 should do just fine.
Or... that JSON file the lambda reads might actually be in a folder and you're trying to read it.
Error 13 usually means you are trying to open a file, but your path is a folder.
Another possible reason for this might be the permission issues on the Lambda handler file.
Try this:
chmod 644 your_lambda_handler_file.py
And in the directory where your lambda code is, try this:
chmod 644 $(find . -type f)
chmod 755 $(find . -type d)

Python 3 - How to chmod all files in a given directory?

In a python 3 script I'm trying to add execution permissions to all .sh files in a directory, as follows:
from os import chmod
chmod('/path_to_dir/dir_prefix_*/bin/*.sh',0o755)
But I'm getting an error:
FileNotFoundError: [Errno 2] No such file or directory:'/path_to_dir/dir_prefix_*/bin/*.sh'
If I run this chmod from bash, it works ok, so I guess python's chmod does not like the use of * in the path.
What would be the correct way to chmod all .sh files in a directory then?
Just use a for loop.
import os
for file in os.listdir("/mydir"):
if file.endswith(".sh"):
chmod(file, mode)

No such file or directory on Mac terminal for python

hello.py is my first python program. It is saved on my desktop.
In the terminal I write in front of
user#AA-MacBook-Air ~ % python3 hello.py
The error is
can't open file 'hello.py': [Errno 2] No such file or directory
Kindly help me understand the problem and solve it.
In the terminal you are currently in the directory ~. This signifies the folder /Users/<username>. Your script is on your desktop.
Type cd Desktop to change to /Users/<username>/Desktop and then run python3 hello.py.
you first need to change destination with cd
The error message, No such file or directory pretty much gives the explanation. Check if the file hello.py is present in the correct working directory. This can done graphically or using the ls command. If it is not present, copy the file the to the directory or navigate to the location of the file hello.py in terminal using cd.

Python won't overwrite 777 file

I have a script that is outputting the pid. I change permissions to 777. Every subsequent instance will overwrite this file with the new pid. Despite the 777 permissions, python reports an OS Error that the operation is not permitted unless the user executing the script is the owner of the file. (I can delete/overwrite the file from the shell, of course).
#!/usr/bin/python
import os
import time
f = open("/tmp/test.txt", 'w')
f.write("Hello, file!\n")
os.chmod("/tmp/test.txt", 0777)
f.close()
$ /tmp/myscript.py # fine
$ sudo -u other_user /tmp/myscript.py #not fine -- gives error
In Linux, only the user who created the file or root can change its permissions. If the file doesn't exist when you call open, you are the owner of the new file and can change its permissions. When the file already exists, it's just truncated and the existing permissions are still in effect. It would be reasonable to just catch and ignore the error because it only happens after the permissions were setup correctly.
If you have the proper permissions in the parent directory, you can delete the file and create a new one each time. But that doesn't work for /tmp because the sticky bit is set and only owner can delete the file.
$ /tmp/myscript.py creates a file owned by you.
and $ sudo -u other_user /tmp/myscript.py means other_user is going to change the file permission owned by you.
same as the following situation:
account1$ touch /tmp/test.txt
account1$ chmod 777 /tmp/test.txt
su account2
account2$ chmod 777 /tmp/test.txt
#chmod: changing permissions of `test.txt': Operation not permitted

Bash can't find right directory in script

I'm making a compress script for my text editor, and it's all working up to the part where it needs to make the file Run. Inside of Run is just this code: python ./App.pyc. When I run the program by double-clicking on it in Finder, it says that it can't open file './App.pyc' [Errno 2] No such file or directory within Terminal.
And if I run it through Terminal after I've cd'd to the directory Run and App.pyc are in, it works. I'm assuming this is because we aren't in the right directory.
My question is, how can I make sure Run is being ran in the right directory? If I put cd in it, it'll work, but then if somebody moves the folder elsewhere it won't work anymore.
#!/usr/bin/python
### Compresser script.
# Compress files.
import App
import Colors
# Import modules
import os
# Clear the folder to put the compressed
# files in (if it exists).
try:
os.system('rm -rf BasicEdit\ Compressed')
except:
pass
# Remake the folder to put compressed files in.
os.system('mkdir BasicEdit\ Compressed')
# Move the compiled files into the BasicEdit
# Compressed folder.
os.system('mv App.pyc BasicEdit\ Compressed/')
os.system('mv Colors.pyc BasicEdit\ Compressed/')
# Create contents of run file.
run_file_contents = "python ./App.pyc\n"
# Write run file.
run_file = open("./BasicEdit Compressed/Run", 'w')
run_file.write(run_file_contents)
# Give permissions of run file to anybody.
os.system('chmod a+x ./BasicEdit\ Compressed/Run')
# Finally compress BasicEdit, and remove the old
# folder for BasicEdit Compressed.
os.system('zip -9r BasicEdit.zip BasicEdit\ Compressed')
os.system('rm -rf BasicEdit\ Compressed')
(PS, what's [Errno 1]? I've never seen it before.)
The Python script's current working directory can be modified with the os.chdir() call, after which references to . will be correct.
If you want to find the location of the source file currently being run rather than hardcoding a directory, you can use:
os.chdir(os.path.dirname(__file__))
The bash equivalent to this logic is:
cd "${BASH_SOURCE%/*}" || {
echo "Unable to change directory to ${BASH_SOURCE%/*}" >&2
exit 1
}
See BashFAQ #28 for more details and caveats.
As developed above together with #William Purcell, you have to retrieve the absolute path by os.pwd() and then use the absolute path for the python call.
I withdraw my proposal and go with #Charles Duffy's answer. However, I don't delete my attempt as the comments seem to be useful to others!

Categories