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)
Related
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 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.
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 have a function that polls a folder for new files, then loads them using numpy.loadtext when it shows up. The function is called from a while loop that runs for 30 seconds. The function works properly most of the time, but for some files, seemingly at random, I get the error IOError: [Errno 13] Permission denied: 'myfilename1.txt'. Here is the content of my function:
before = dict([(f, None) for f in os.listdir(mydir)])
while 1:
after = dict([(f, None) for f in os.listdir(mydir)])
added = [f for f in after if f not in before]
# New File
if added:
raw = numpy.loadtxt(mydir + added[0])
return raw
Any idea on why this is happening? It properly polls and reads most text files that are incoming, but sometimes spits the error and I can't find a systematic reason why.
UPDATE:
Has something to do with using the full path with loadtxt. When I change the working directory to the directory where the files are, I no longer get the permissions error.
Have you tried opening the file as read only, may be a conflict if the file is accessed by another application (or is still currently being created).
# New File
if added:
with open(mydir + added[0], 'r') as f:
raw = numpy.loadtxt(f)
You could also try some form of IOError handling which waits a little while and then tries again
import time
before = dict([(f, None) for f in os.listdir(mydir)])
added = False
while 1:
# New File
if added:
try:
raw = numpy.loadtxt(mydir + added[0])
return raw
except IOError:
time.sleep(5)
else:
after = dict([(f, None) for f in os.listdir(mydir)])
added = [f for f in after if f not in before]
I got the same error when I attempted the following:
Y = np.loadtxt("C:/Users/erios/images_3_color_15k_labeled/", dtype='int')
I.e., I passed the folder where the text was located
INstead, the following command executed with no error:
Y = np.loadtxt("C:/Users/erios/images_3_color_15k_labeled/labels_for_locations.txt", dtype='int')
In sum, specify the full name of the text file, not just the folder.
I have made a program, and there is a function where it gets a text file called news_2014.txt from a ftp server. I currently have this code:
def getnews():
server = 'my ftp server ip'
ftp= ftplib.FTP(server)
username = 'news2'
password = ' '
ftp.login(username,password)
filename = 'ftp://my ftp server ip/news/news_2014.txt'
path = 'news'
ftp.cwd(path)
ftp.retrlines('RETR' + filename, open(filename, "w").open)
I wanna make so the program displays the lines using readlines onto a Tkinter label. But if I try calling the top function, it says:
IOError: [Errno 22] invalid mode ('w') or filename: 'ftp://news/news_2014.txt'
RETR wants just the remote path name, not a URL. Similarly, you cannot open a URL; you need to pass it a valid local filename.
Changing it to filename = 'news_2014.txt' should fix this problem trivially.
The retrlines method retrieves the lines and optionally performs a callback. You have specified a callback to open a local file for writing, but that's hardly something you want to do for each retrieved line. Try this instead:
textlines = []
ftp.retrlines('RETR ' + filename, textlines.append)
then display the contents of textlines. (Notice the space between the RETR command and its argument, too.)
I would argue that the example in the documentation is confusing for a newcomer. Someone should file a bug report.