I am writing a Python script that checks if a folder exists, deleting it if it does, and then rewrites it.
I can create a directory, then immediately delete it.
But when I try to delete a directory, then create one, I get the following error:
"[Error 5] Access is denied: 'plots'"
While:
os.path.exists(dir)=false
Perhaps Spyder is reserving the memory somehow? Please help!
import os, shutil
dir = 'plots'
print "remove directory"
if os.path.exists(dir):
shutil.rmtree(dir)
print os.path.exists(dir)
print "create directory"
os.mkdir(dir, 0755)
print os.path.exists(dir)
EDIT:
Output first run (when 'plots' doesn't exist)
remove directory
False
create directory
True
Output second run (when 'plots' does exist)
remove directory
False
create directory
File "C:/Python27/Spyder Workspace/JPL_impact_gnuplot/07gnuplot/02my_lammps_anal/anal_lammps.py", line 60, in
os.mkdir(dir, 0755)
WindowsError: [Error 5] Access is denied: 'plots'"
So, at the end:
os.path.exists(dir)=false
But access to that dir is surprisingly denied! Help!
This could happen if your environment does not have write permissions to the directory.
You can recreate the scenario from the command line.
$ touch testfile
$ ls testfile
testfile
$ chmod 555 .
$ rm testfile
$ ls testfile
ls: cannot access testfile: No such file or directory
$ touch testfile
touch: cannot touch `testfile': Permission denied
Related
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)
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.)
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
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!
I'm working on a test case for which I create some subdirs. However, I don't seem to have the permission to remove them anymore. My UA is an Administrator account (Windows XP).
I first tried:
folder="c:/temp/"
for dir in os.listdir(folder):
os.remove(folder+dir)
and then
folder="c:/temp/"
os.remove(folder+"New Folder")
because I'm sure "New Folder" is empty. However, in all cases I get:
Traceback (most recent call last):
File "<string>", line 3, in <module>
WindowsError: [Error 5] Access is denied: 'c:/temp/New Folder'
Does anybody know what's going wrong?
os.remove requires a file path, and raises OSError if path is a directory.
Try os.rmdir(folder+'New Folder')
Which will:
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.
Making paths is also safer using os.path.join:
os.path.join("c:\\", "temp", "new folder")
try the inbuilt shutil module
shutil.rmtree(folder+"New Folder")
this recursively deletes a directory, even if it has contents.
For Python 3.6, the file permission mode should be 0o777:
os.chmod(filePath, 0o777)
os.remove(filePath)
os.remove() only works on files. It doesn't work on directories. According to the documentation:
os.remove(path)
Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
use os.removedirs() for directories
U can use Shutil module to delete the dir and its sub folders
import os
import shutil
for dir in os.listdir(folder):
shutil.rmtree(os.path.join(folder,dir))
Use os.rmdir instead of os.remove to remove a folder
os.rmdir("d:\\test")
It will remove the test folder from d:\\ directory
If you want remove folder, you can use
os.rmdir(path)
If it's a directory, then just use:
os.rmdir("path")
File is in read only mode so change the file permission by os.chmod() function and then try with os.remove().
Ex:
Change the file Permission to 0777 and then remove the file.
os.chmod(filePath, 0777)
os.remove(filePath)
The reason you can't delete folders because to delete subfolder in C: drive ,you need admin privileges
Either invoke admin privileges in python or do the following hack
Make a simple .bat file with following shell command
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\temp\*.*") DO rmdir "%%p" /s /q
Save it as file.bat and call this bat file from your python file
Bat file will handle deleting subfolders from C: drive
Can't remove a folder with os.remove
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
In my case it was due to lack of admin privileges.
I solved it running terminal or cmd as administrator
windows key -> cmd -> right click -> run as administrator