Python open and "permission denied" on file with ugo+rw? - python

I have a script on a RHEL 7.x machine written in Python3. In testing this script I created a function which will append to a text file in the same directory.
If I execute the script from the local directory ie - ./pyscript.py everything works as expected.
But I am trying to execute this from a Bash script a couple directories higher and it doesn't seem to work right. The other functions in the script will execute, but this very last one which appends to a text file will not.
Now, if I run the script as the user which owns it(and the txt file) from my home dir, the script errors out with a permission error. BUT if I run the script with sudo it finishes with NO error, However it does NOT write to the text file.
My user has RW privileges on every dir between the bash script and the python script.
Any thoughts on why a sudo or local user run doesn't seem to let me write to the text file??
Edit
Traceback (most recent call last):
File "ace/ppod/my_venv/emergingThreats/et_pro_watchlists.py", line 165, in <module>
with open('etProLog.txt', 'a') as outlog:
PermissionError: [Errno 13] Permission denied: 'etProLog.txt'

If you use open("filename.txt", 'mode'), it will open that file in the directory from which the script is executed, not relative to the current directory of the script. If you want the path to directory where the script exists, import the os module and use open(os.path.dirname(os.path.abspath(__file__))+"filename.txt"). The permission error is because the file doesn't exist; sudo overrides that but does nothing because the file doesn't exist.

Related

Python Executable, PermissionError: [WinError 5]

I'm trying to write a chatting app that when run the first time deletes itself from the current position. Now the code is:
import os
import sys
file=sys.argv[0]
os.remove(file)
if i run it as .py file, it works just fine. Anyway if compile it with pyinstaller, when run by terminal it raises:
Traceback (most recent call last):
File "tests.py", line 6, in <module>
PermissionError: [WinError 5] Denied access: 'tests.exe'
[14320] Failed to execute script 'tests' due to unhandled exception!
nothing changes if i run it as administrator or assigning the file permissions with os.chmod. I have python 3.10, i tried both with python 3.9 and 3.10 and it does not work. I even tried running the command del with the subprocess module with the same result.
This works as .py file because the actual executable is the compiled version of the source code - a separate file/memory space. While the compilation is running the source code .py file is closed and can be removed.
When the program is compiled and run as a .exe file it will not remove itself because it is still open and running and therefore has a permission access denied error.
It is trying to remove itself because file = sys.argv[0]
(If you want to remove your running exe maybe start another program that does the removing from the exe and exit exe so that it is closed before removal - kind of awkward.)

How to run a Python script in VSCode using the same path of the script? (otherwise it can't find an input file located in the same folder)

I have this Python code: https://github.com/andreagrandi/aoc_2019/tree/master/aoc
which runs perfectly from the terminal (Python 3 required) if I do for example: python aoc_03.py
But if I try to run it from VSCode, taking advantage of the Python extension and integration, I get this error:
(aoc) ➜ advent_of_code_2019 git:(master) /Users/andrea/.virtualenvs/aoc/bin/python /Users/andrea/Documents/advent_of_code_2019/aoc/aoc_03.py
Traceback (most recent call last):
File "/Users/andrea/Documents/advent_of_code_2019/aoc/aoc_03.py", line 70, in <module>
with open('aoc_03_input.txt', 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aoc_03_input.txt'
My guess is that when invoked from VSCode, the script is run from a different path, so it cannot find the file aoc_03_input.txt which is located in the same folder of the script.
How do I tell VSCode to run my script from the /Users/andrea/Documents/advent_of_code_2019/aoc/ folder, so that it will be able to find my input file?
Thanks
Actually, I should have tried more before asking this question, because I just found the solution, but at this point I will write it here in case it can be useful to anyone:
If I change the path in this way:
with open('./aoc_03_input.txt', 'r') as file:
The file is being open correctly when I run the code in VSCode and when I run it from the terminal. Tested under OSX (but it should work under Linux too. Not sure about Windows).

Error with Reading Files

I am working through Learn Python the Hard Way but am having a problem with an exercise that reads a file: https://learnpythonthehardway.org/python3/ex15.html
I have followed this and made sure my file is in the same folder as my python file. I keep getting the error:
Traceback (most recent call last):
File "ex15.py", line 5, in <module>
txt = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ex15_sample.txt'
I am entering: python ex15.py ex15_sample.txt into the powershell. I tried looking up the problem I'm having but could not find anything that helped in my case. Let me know if I am doing something wrong or if I'm missing something. Thanks
You can check your current path and whether your file exists by
import os
#get the current working directory
os.getcwd()
#check whether your file exists in the current working directory
os.path.exists("./ex15.py")
try 2 things below
Check both files .py and .txt are at same location. and then execute program.
this is how i ran the code.
C:\Users\db\Desktop\Python>python ex15.py
enter File Name: ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
If your file is at other location you need to provide absolute path for your file. as
C:\Users\db\Desktop\Python>python C:\Users\deepakb\Desktop\ex15_sample.txt
i had my txt file at desktop this time.
A brief demonstration on working directory and relative file locations..
Say we have a text file named hello.txt with the contents:
Hello World!
that is located at "C:\Users\username\Documents\python\hello.txt"
And we have a python script named script.py with the contents:
with open('hello.txt', 'r') as f:
print(f.read())
Which is located at "C:\Users\username\Documents\python\script.py"
If I just hit the windows key and type power shell and hit enter to open it, I'll see it by default gives me a prompt at my home directory: "C:\Users\username>". From here I can execute my python script by calling C:\Users\username> python C:\Users\username\Documents\python\script.py. If I do this, however, they python interpreter would have started in my home folder, and when it tries to find "hello.txt" it will only search through the folder "C:\Users\username". That's not where the file is, so we get a file not found error.
To resolve this we have a few options. Number one is to re-write our script file to include the full path of our text file: ... open("C:/Users/username/Documents/python/hello.txt", ... This way there is no searching necessary, and the script can be run from anywhere. Another option is to change the working directory of the interpreter from within the script. You can set the working directory with the os library by calling os.chdir('C:/Users/username/Documents/python'). Finally you can set the working directory with PowerShell before calling the python interpreter using the cd command:
C:\Users\username> cd .\Documents\python\
I had the same error.
It was a mistake from me naming the file as ex15_sample.txt.
When you are creating a file in notepad, the file name would be automatically .txt
so if you have created a file just rename it as ex15_sample.
or
You can also run the same program by giving python ex15.py ex15_sample.txt.txt
As you can see the file name might be ex15_sample.txt with a .txt extension.

Permission Denied even after chmod 777

I have a python script that needs to access 3 files in a folder. When I run the script I get the following:
$ python mqtt_pub_test.py
Traceback (most recent call last):
File "mqtt_pub_test.py", line 10, in <module>
mqttc.tls_set(my_ca_cert, certfile=my_pri_cert, keyfile=my_key_cert)
File "C:\Python27\lib\site-packages\paho\mqtt\client.py", line 557, in tls_set
raise IOError(ca_certs+": "+err.strerror)
IOError: C:\Users\<user>\my_phone_certs: Permission denied
In an attempt to fix this I ran chmod 777 on everything in that path, even down to the files themselves!
The variables in mqttc.tls_set are pointing to the folder locations.
I have no idea why I am still getting permission denied at this point.
Any suggestions?
You are trying to access files which can not be edited:
mqttc.tls_set(my_ca_cert, certfile=my_pri_cert, keyfile=my_key_cert)
You could run the script as superuser (sudo python mqtt_pub_test.py), if in Linux.
If you are running in a cygwin like environment (which you described in the comments) you should use as file descriptor or let's say file pointer something like /cygdrive/c/Users/yourusername/phone_certs (or for git bash for instance /c/Users/youruser/phone_certs).
I would really suggest that you would move to cygwin entirely as it gives you a more complete linux-like environment on Windows which is very convenient to work with.

Permission denied error while writing to a file in Python

I want to create a file and write some integer data to it in python. For example, I have a variable abc = 3 and I am trying to write it to a file (which doesn't exist and I assume python will create it on its own):
fout = open("newfile.dat", "w")
fout.write(abc)
First, will python create a newfile.dat on its own? Secondly, it's giving me this error:
IOError: [Errno 13] Permission denied: 'newfile.dat'
What's wrong here?
Please close the file if its still open on your computer, then try running the python code.
I hope it works
This also happens when you attempt to create a file with the same name as a directory:
import os
conflict = 'conflict'
# Create a directory with a given name
try:
os.makedirs(conflict)
except OSError:
if not os.path.isdir(conflict):
raise
# Attempt to create a file with the same name
file = open(conflict, 'w+')
Result:
IOError: [Errno 13] Permission denied: 'conflict'
I've had the same issue using the cmd (windows command line) like this
C:\Windows\System32> "G:\my folder\myProgram.py"
Where inside the python file something like this
myfile = open('myOutput.txt', 'w')
The error was that when you don't use a full path, python would use your current directory, and because the default directory on cmd is
C:\Windows\System32
that won't work, as it seems to be write-protected and needs permission & confirmation form an administrator
Instead, you should use full paths, for example:
myfile = open('G:\my folder\myOutput.txt', 'w')
Permission denied simply means the system is not having permission to write the file to that folder. Give permissions to the folder using "sudo chmod 777 " from terminal and try to run it. It worked for me.
I write python script with IDLE3.8(python 3.8.0)
I have solved this question:
if the path is
shelve.open('C:\\database.dat')
it will be
PermissionError: [Errno 13] Permission denied: 'C:\\database.dat.dat'.
But when I test to set the path as
shelve.open('E:\\database.dat')
That is OK!!!
Then I test all the drive(such as C,D,F...) on my computer,Only when the Path set in Disk
C:\\
will get the permission denied error.
So I think this is a protect path in windows to avoid python script to change or read files in system Disk(Disk C)
In order to write on a file by using a Python script, you would have to create a text file first.
Example A file such as C:/logs/logs.txt should exist.
Only then the following code works:
logfile=open(r"C:/logs/logs.txt",'w')
So summary.
A text file should exist on the specified location
Make sure you close the file before running the Python script.
To answer your first question: yes, if the file is not there Python will create it.
Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.
If you are executing the python script via terminal pass --user to provide admin permissions.
Worked for me!
If you are using windows run the file as admin.
If you are executing via cmd, run cmd as admin and execute the python script.
Make sure that you have write permissions for that directory you were trying to create file by properties

Categories

Resources