I'm trying to upload some files to Dropbox using Python and the Dropbox api.
This is what I have so far -
import sys
import dropbox
import time
from dropbox.files import WriteMode
from dropbox.exceptions import ApiError, AuthError
# Access dropboxToken
dropboxToken = '<token>'
localPath = '<local path in Downloads folder>'
uploadPath = '<dropbox path>'
# Uploads contents of localFile to Dropbox
def upload():
with open(localPath, 'rb') as f:
for file in localPath:
# We use WriteMode=overwrite to make sure that the settings in the file
# are changed on upload
print('Uploading ' + localFile + ' to Dropbox location ' + uploadPath)
try:
dbx.files_upload(f.read(), uploadPath, mode=WriteMode('overwrite'))
except ApiError as err:
# This checks for the specific error where a user doesn't have enough Dropbox space quota to upload this file
if (err.error.is_path() and
err.error.get_path().error.is_insufficient_space()):
sys.exit('ERROR: Cannot upload file; insufficient space.')
elif err.user_message_text:
print(err.user_message_text)
sys.exit()
else:
print(err)
sys.exit()
if __name__ == '__main__':
print('Uploading file(s)...')
# upload the files
upload()
Whenever I run it I receive the following message: PermissionError: [Errno 13] Permission denied
I've read some other threads about running IDLE as admin, executing the file from the command line as admin, checking the permissions of the file path, etc. but none of those suggestions are working. Is there something wrong with my code, or something else I'm not thinking of?
I'm on Windows 10 and my account is a local administrator, and I'm using Python 3.8.1. Any help is greatly appreciated.
Related
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?
I'm trying to download a file from this website with python.
I however get this error:PermissionError: [WinError 5] Access is denied: 'C:\\Users\\testuser'
Note that I cannot run this code as admin. It has to be solved somehow programmatically
This is the code:
import os
import stat
import requests
def download(url_string: str, destination_folder: str):
if not os.path.exists(destination_folder):
os.makedirs(destination_folder) # create folder if it does not exist
filename = url_string.split('/')[-1].replace(" ", "_") # be careful with file names
file_path = os.path.join(destination_folder, filename)
r = requests.get(url_string, stream=True)
if r.ok:
print("saving to", os.path.abspath(file_path))
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024 * 8):
if chunk:
f.write(chunk)
f.flush()
os.fsync(f.fileno())
else: # HTTP status code 4XX/5XX
print("Download failed: status code {}\n{}".format(r.status_code, r.text))
url = r'https://www.dundeecity.gov.uk/sites/default/files/publications/civic_renewal_forms.zip'
path = r'C:\Users\testuser\Desktop\report\report.zip'
download(url, path)
Go to Start > Settings > Update & Security > Windows Security > Virus & threat protection.
then, click exclusions and add your python file.
I solved it!
First of all, I've apparently misspelled the username of the computer: it's test_user. Silly, I know, but difficult until you see it.
Second of all python apparently seems to want to force me to make this file a txt. Had to force it myself to make it a Zip.
Okay.
Glad it was fixed quickly. Thanks for the support :D
I'm using this to connect to Azure File Share and upload a file. I would like to chose what extension file will have, but I can't. I got an error shown below. If I remove .txt everything works fine. Is there a way to specify file extension while uploading it?
Error:
Exception: ResourceNotFoundError: The specified parent path does not exist.
Code:
def main(blobin: func.InputStream):
file_client = ShareFileClient.from_connection_string(conn_str="<con_string>",
share_name="data-storage",
file_path="outgoing/file.txt")
f = open('/home/temp.txt', 'w+')
f.write(blobin.read().decode('utf-8'))
f.close()
# Operation on file here
f = open('/home/temp.txt', 'rb')
string_to_upload = f.read()
f.close()
file_client.upload_file(string_to_upload)
I believe the reason you're getting this error is because outgoing folder doesn't exist in your file service share. I took your code and ran it with and without extension and in both situation I got the same error.
Then I created a folder and tried to upload the file and I was able to successfully do so.
Here's the final code I used:
from azure.storage.fileshare import ShareFileClient, ShareDirectoryClient
conn_string = "DefaultEndpointsProtocol=https;AccountName=myaccountname;AccountKey=myaccountkey;EndpointSuffix=core.windows.net"
share_directory_client = ShareDirectoryClient.from_connection_string(conn_str=conn_string,
share_name="data-storage",
directory_path="outgoing")
file_client = ShareFileClient.from_connection_string(conn_str=conn_string,
share_name="data-storage",
file_path="outgoing/file.txt")
# Create folder first.
# This operation will fail if the directory already exists.
print "creating directory..."
share_directory_client.create_directory()
print "directory created successfully..."
# Operation on file here
f = open('D:\\temp\\test.txt', 'rb')
string_to_upload = f.read()
f.close()
#Upload file
print "uploading file..."
file_client.upload_file(string_to_upload)
print "file uploaded successfully..."
I a have flask based web service where I trying to download the results to a file to user's desktop (via https).
I tried :
def write_results_to_file(results):
with open('output', 'w') as f:
f.write('\t'.join(results[1:]) + '\n')
this method gets activated when I click export button in the ui.
But I am getting :
<type 'exceptions.IOError'>: [Errno 13] Permission denied: 'output'
args = (13, 'Permission denied')
errno = 13
filename = 'output'
message = ''
strerror = 'Permission denied'
Can some one tell me what I am doing wrong here ?
Can some one tell me what I am doing wrong here ?
The function you posted isn't an actual Flask view function (app.route()), so it isn't entirely clear what your server is doing.
This may be closer to the code you need:
#app.route("/get_results")
def get_results():
tsv_plaintext = ''
# I'm assuming 'results' is a 2D array
for row in results:
tsv_plaintext += '\t'.join(row)
tsv_plaintext += '\n'
return Response(
tsv_plaintext,
mimetype="text/tab-separated-values",
headers={"Content-disposition":
"attachment; filename=results.tsv"})
(With assistance from Flask: Download a csv file on clicking a button)
I am using jquery+ajax to transfer a file to the server. In the server I have a python script which I copy below which simply gets the file and writes it on disk. The script works perfect for bytes smaller than 1 Kby but for bigger files it throws an exception: OSError: [Errno 13] Permission denied
Why does this happen? I do not have access to the server. Should I ask something to the server administrator?
#!/usr/local/bin/python
import cgi, os
import cgitb; cgitb.enable()
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
form = cgi.FieldStorage()
# A nested FieldStorage instance holds the file
fileitem = form['photo']
# Test if the file was uploaded
fn = os.path.basename(fileitem.filename)
# strip leading path from file name to avoid directory traversal attacks
if fileitem.filename:
fn = fileitem.filename
open('fotos/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
you don't have permission to open (or write?) whatever file you are trying to work with. Try running the script as super user or change permissions on the directory where you are trying to read/write from
From the getcwd man page:
EACCES
Permission to read or search a component of the filename was denied.
So it sounds like you (or whatever user your server is running as) don't have read permissions for part of your current path. Are you across a mount point, perhaps? Or changed the permissions for one of the parent directories?
The problem was that the server was not configured to accept files with a size larger than 1 Kby. The solution was asking the server administrator to change this configuration.