Errno 13 Permission denied.... I can't access this JSON file - python

I am trying to open a JSON file.
Here is my code:
import json
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
data = json.loads(fh)
for i in data:
print(i)
However, I keep getting the error:
Traceback (most recent call last):
File "C:\Users\Joker\Desktop\Python\jsondatabase.py", line 3, in <module>
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
PermissionError: [Errno 13] Permission denied: 'C:/Users/Joker/Desktop/Python/Code3/roster'
[Finished in 0.135s]
How can I access the data?
Edit: It worked when I ran as admin. Thanks everyone!

The code as written orphans the file handler, leaving it open. It may very well be open in another program which is hard to see from the process manager, but you should edit to:
import json
with open('C:/Users/Joker/Desktop/Python/Code3/roster.json', "r") as fh:
data = json.load(fh)
for i in data:
print(i)
To clear the orphaned handler you could try wack-a-mole with the task manager or just restart your machine.

Related

PermissionError: [Errno 13] Permission denied: 'C:/Windows/System32/drivers/etc/host

This is Python code for website blocking. I am using Jupyter notebook to run this code. When I run this program I am getting error name as PermissionError.
import datetime
import time
end_time=datetime.datetime(2022,9,22)
site_block=["www.wscubetech.com","www.facebook.com"]
host_path="C:/Windows/System32/drivers/etc/hosts"
redirect="127.0.0.1"
while True:
if datetime.datetime.now()<end_time:
print("Start Blocking..")
with open(host_path,"r+") as host_file:
content = host_file.read()
for website in site_block:
if website not in content:
host_file.write(redirect+" "+website+"\n")
else:
pass
else:
with open(host_path,"r+") as host_file:
content = host_file.readlines()
host_file.seek(0)
for lines in content:
if not any(website in lines for website in site_block):
host_file.write(lines)
host_file.truncate()
time.sleep(5)
This is the error I get when I run this program:
PermissionError
Traceback (most recent call last)
Input In [15], in <cell line: 8>()
9 if datetime.datetime.now()<end_time:
10 print("Start Blocking..")
---> 11 with open(host_path,"r+") as host_file:
12 content = host_file.read()
13 for website in site_block:
PermissionError: [Errno 13] Permission denied: 'C:/Windows/System32/drivers/etc/hosts
Permission denied simply means the system is not having permission to open the file to that folder.
C:\Windows\System32\drivers\etc\hosts is writable only by the Administrator. You should run your script in Administrator mode.
EDIT (23/09/2022 - comment):
I ran your code with pycharm in administrator mode, no error and no output but the file was modified (two extra lines then deleted):
I rewrote the code for testing. Here it is for a different approach:
site_block = ["www.facebook.com", "www.stackoverflow.com"]
host_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
with open(host_path, "r+") as host_file:
for website in filter(lambda website: website not in host_file.read(), site_block):
host_file.write(redirect + " " + website + "\n")
time.sleep(5)
with open(host_path, "r") as host_file:
lines = host_file.readlines()
with open(host_path, "w") as output:
for line in lines:
if not any(redirect + " " + website + "\n" == line for website in site_block):
output.write(line)
Tips:
You can use a boolean to know if you have already updated the file to avoid opening it every 5 seconds.
You can stop the process after cleaning the file.
You can also look to run the code with a cron.
The PermissionError is caused when you do not have a permission to do something.
The file C:/Windows/System32/drivers/etc/hosts is protected by the permission. That is why you cannot access to it.
Why don't you run it as administrator?

Why I get PermissionError if file is closed? (Python)

I get this error while I'm running my code:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: error
but my file is closed, can you please help?
def delete_employee(self, new_employee):
employees_csv_data = self.open_and_read_file(self.list_of_employees)
with open(EMPLOYEES_EDIT_FILE, 'w') as updated_csv:
writer = csv.writer(updated_csv)
if str(new_employee.employee_id) not in str(employees_csv_data.values):
print(EMPLOYEE_DOESNT_EXIST_IN_FILE_MSG)
else:
for row in employees_csv_data.values:
if new_employee.employee_id != str(row[0]):
writer.writerow(row)
os.rename(EMPLOYEES_EDIT_FILE, self.list_of_employees)
os.remove(self.list_of_employees)
Looks like some other application is accessing this file. Try to delete it and create it again or restart the system.

Selenium after take screenshot unlink txt file

I have some txt files in a folder, I have listed directory and garbed links. After visit links using selenium I have taken screenshot. Now I am trying do delete this link txt file.
Below code I have tried
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import os
path = "E:/xampp/htdocs/spool/"
directories = os.listdir(path)
for dir in directories:
# print(dir)
files = os.listdir(path+dir)
for file in files:
# print(path+dir+'/'+file)
f = open(path+dir+'/'+file, "r")
list = f.read()
data = list.split("||")
print(data[1])
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(data[1])
driver.save_screenshot(data[0]+'.png')
driver.close()
os.unlink(f.name)
Problem is unlink time it's giving below error
Traceback (most recent call last):
File "index.py", line 21, in <module>
os.unlink(f.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'E:/xampp/htdocs/spool/7/2020-09-1112.txt'
I have also used os.close(3), After that got error "
list = f.read()
OSError: [Errno 9] Bad file descriptor
"
How can I unlink after take screenshot ?
Version python : Python 3.8.4
As u can see another process is using the txt file.
I think that's the problem here; you opened the file and didn't closed it.
I suggets you to visit https://www.tutorialspoint.com/python/file_close.htm
Try to call f.close() and then unlink.
This method of file handling is not entirely safe.
If an exception occurs when we are performing some operation with the file, the code exits with out closing the file.
In your case you forgot to close the file.
f.close()
I would recommend to use this approach to avoid such scenarios
with open("test.txt", mode= 'r', encoding = 'utf-8') as f:
# perform file operations
pass
# we dont need to explicitly close() the method, it is done internally.

Access html file in write mode using python

example.py
file = open("innovative.html", "w")
file.write("This is a test\n")
file.write("And here is another line\n")
file.close()
return render_template('innovative.html')
while I am executing this file in server it throwing [Errno 13] Permission denied: 'innovative.html'
I am executing this file in rhcloud.
I changed permissions for file as -rwx- for innovative.html
Thanks in advance.
This error can occur when a file is actively opened or utilized by another process at the same time (as well as when permissions are not given). Be sure to check that the file is not being used while attempting to write.

Python - IOError: [Errno 2] No such file or directory: u'lastid.py' for file in same directory. Works locally, doesn't on Heroku

I suspect this is a very newbie question but I can't find any solutions that are helping :(
I've been trying to get started with Python by building a simple Twitter bot which replies to people who tweet at it. It worked locally, and it doesn't work on Heroku.
A quick rundown: Each time the bot tweets, it uses a script called mainscript.py which writes the ID of the last tweet replied to into a separate file called lastid.py. The next time the script runs, it opens lastid.py, checks the number inside against the current list of tweets, and only responds to those with a larger ID number than the one stored in lastid.py.
fp = open("lastid.py", 'r')
last_id_replied = fp.read()
fp.close()
#(snipped - the bot selects the tweet and sends it here...)
fp = open("lastid.py", 'w')
fp.write(str(status.id))
fp.close()
This works great locally. Runs fine. However, when I upload it to Heroku I get this error:
Traceback (most recent call last):
File "/app/workspace/mainscript.py", line 60, in <module>
fp = open("lastid.py", 'r')
IOError: [Errno 2] No such file or directory: u'lastid.py'
I am absolutely 100% positive lastid.py and mainscript.py are on the server and inside the same directory - I have triple-checked this by running bash on heroku. My .gitignore file is blank so it isn't anything to do with that.
I don't understand why such a simple command as 'open a file in the same directory and read it' doesn't work on the server. What on earth have I done wrong?
(I realise I should have worked through some tutorials before trying to build something custom in a new language, but now I've started this I'd really love to finish it - any help anyone can offer would be very much appreciated.)
Probably the python interpreter is being executed from a different directory than where your script lives.
Here's the same setup:
oliver#aldebaran /tmp/junk $ cat test.txt
a
b
c
baseoliver#aldebaran /tmp/junk $ cat sto.py
with open('test.txt', 'r') as f:
for line in f:
print(line)
baseoliver#aldebaran /tmp/junk $ python sto.py
a
b
c
baseoliver#aldebaran /tmp/junk $ cd ..
baseoliver#aldebaran /tmp $ python ./junk/sto.py
Traceback (most recent call last):
File "./junk/sto.py", line 1, in <module>
with open('test.txt', 'r') as f:
IOError: [Errno 2] No such file or directory: 'test.txt'
To solve this, import os and use absolute pathnames:
import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
pass
# and so on

Categories