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

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)

Related

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.

Reading file from one up directory in python2.7

I am trying to read file in a python script from one up level.
My file structure is as below:
code
- scripts
-myscript.py
- .env
In .env I have my configs.
And I am trying to read this file in myscript.py
I did the below to read it:
envfile = open("../.env", "r")
Now when I run this python script from the scripts directory it works fine
This works good:
cd /var/www/html/code/scripts
python myscript.py
But if I do:
cd
python /var/www/html/code/scripts/myscript.py
Doesn't work and gives IOError: [Errno 2] No such file or directory: '../.env'
How can I make it to run if I pass the absolute or relative path in terminal?
You can use pathlib2:
pathlib2 is the version for python 2.7
pathlib Module: Taming the File System
from pathlib import Path
path = Path(__file__).resolve().parents[1].joinpath(".env")
envfile = open(path)
import os
p = os.path.realpath(__file__)
envfile = open('/'.join(p.split('/')[:-1])+'/../.env')
also works

Permission denied on shutil.move on image files

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.)

execute a python file globally from any path - windows7

I have a script abc.py under C:\Python\Python35\Scripts\ folder and I have C:\Python\Python35\python.exe;C:\Python\Python35\Scripts;C:\Python\Python35; in my PATH. Still I'm not able to execute the python from anywhere else otherthan its directory.
For example, I always have to go to C:Python\Python35\Scripts and then execute python abc.py. Else, it is giving below error -
python: can't open file 'abc.py': [Errno 2] No such file or directory
Any help here is much appreciated.

Python - can not delete, then create folder

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

Categories