Save xlsx file in Desktop using Django - python

I want to save a excel file in Desktop from my apps, the file path is depends on the user that she/he want to download the file.Give me some idea, Thank You.
FileNotFoundError at /Registration/Registration/Report [Errno 2] No
such file or directory:
'/Users/{username}/Desktop/Registration_Report.xlsx'
I got the error above if I call the current username login:
import os
def registration_report(request):
username = os.getlogin()
***excel codes here***
wb.save("/Users/{username}/Desktop/Registration_Report.xlsx") ## path to save the xlsx file ##
If I put the exact path to desktop working good and I access the downloaded excel file, This is working but what I want is, the path is depend on the user machine where the file to save.
def registration_report(request):
***excel codes here***
wb.save("/Users/myusername/Desktop/Registration_Report.xlsx")
***myusername is the exact machine login username that I use***

Your issue is here:
"/Users/{username}/Desktop/Registration_Report.xlsx"
This is just a string. In order to inject the username value you need an f-string.
wb.save(f"/Users/{username}/Desktop/Registration_Report.xlsx")

Related

Is there a way to execute a file knowing only the subdirectory?

I have two exe files located at
C:\Users\Bella\Desktop\Folder\fuctions
I want to write a python script that would open them both from Desktop\Folder, The issue is I want to share this script with people and I won't know the name of their User,
Is there a way to execute the files while only knowing it will be in Folder\functions since I will always know that my script will be located in "Folder"
import os
os.startfile(r"C:\Users\Bella\Desktop\Folder\Dist\fuctions\Test.exe")
os.startfile(r"C:\Users\Bella\Desktop\Folder\Dist\fuctions\Test2.exe")
obviously that wont work when shared to friends
You can use relative path as mentioned in the comments or use:
import os
# get the directory of the file
dir = os.path.realpath('...')
# append the remainder of the path
path = os.path.join(dir, 'Dist\fuctions\Test.exe')
Use os.environ.get("USERNAME")
It gets the username of the user.
import os
username = os.environ.get("USERNAME")
os.startfile(f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test.exe")
os.startfile(r=f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test2.exe")
Or you can use os.getlogin()
import os
username = os.getlogin()
os.startfile(f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test.exe")
os.startfile(r=f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test2.exe")
Upvote if it works :)

Chron - [Permission Denied] when I try to save & remove file from directory

Issue: Unable to save file in directory (/root/Notion/Image) when using Cron schedule
This is what my code is trying to do:
Check email
Download image attachment
Store in a directory - root/Notion/Image
Retrieve file path
The script is working when I run it manually in Google Cloud terminal. The problem is when I try to schedule it on Cron, it's unable to access the folder to save the file locally.
This is the error when the script failed and require permission:
Traceback (most recent call last):
File "Notion/test.py", line 121, in <module>
path = get_attachments(email.message_from_bytes(msg[0][1]))
File "Notion/test.py", line 47, in get_attachments
with open(filePath, 'wb') as f:
PermissionError: [Errno 13] Permission denied: '/root/Notion/Image/3.jpeg'
This is the code to retrieve attachment from email
def get_attachments(msg):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath, 'wb') as f:
f.write(part.get_payload(decode=True))
return str(filePath)
Resolved:
The problem is that I shouldn't use root directory since it requires permission. I've changed it to home directory instead.
attachment_dir = '/home/dev_thomas_yang/folder_name/folder_name'
For people who needs to check their home direction, simply run this script.
from pathlib import Path
home= str(Path.home())
print(home)
Thanks Triplee for the patience to breakdown my issue despite my sloppy ways of presenting it!
The easiest fix hands down is to change the code so it doesn't try to write to /root. Have it write to the invoking user's home directory instead.
Your question doesn't show the relevant parts of the code, but just change attachment_dir so it's not an absolute path. Maybe separately take care of creating the directory if it doesn't already exist.
import pathlib
# ...
attachment_dir = pathlib.Path("cron/whatever/attachments").mkdir(parents=True, exist_ok=True)
# ...
for loop in circumstances:
get_attachments(something)
A better design altogether would be to have get_attachments accept the directory name as a parameter, so you can make this configurable from the code which calls it. Global variables are a nuisance and cause hard-to-debug problems because they hide information which is important for understanding the code, and tricky to change when you try to debug that code and don't know which parts of the code depend on the old value.

Load a gpx file on python

I'm a Mac user. I'm trying to load a .gpx file on python,using the following code:
import gpxpy
import gpxpy.gpx
gpx_file = open('Downloads/UAQjXL9WRKY.gpx', 'r')
And I get the following message:
FileNotFoundError: [Errno 2] No such file or directory: 'Downloads/UAQjXL9WRKY.gpx'
Could someone help me figure out why? Thanks in advance.
Obviously, one reason would be that the file does not, in fact, exist, but let us assume that it does.
A relative filename (i.e, one that does not start with a /) is interpreted relative to the current working direcory of the process. You are apparently expecting that to be the user's home directory, and you are apparently wrong.
One way around this would be to explicitly add the user's home directory to the filename:
import os
home = os.path.expanduser('~')
absfn = os.path.join(home, 'Downloads/whatever.gpx')
gpx_file = open(absfn, ...)

Access Denied to zipfile created using python

I was able to create a zip file using the below code:
import os
import zipfile
user = input('Please enter your ID:')
date = input('Please enter the date:')
os.chdir('C:/Users/'+user+'/Desktop/Files/')
name = 'Position_'+date+'_Global'
newzip = zipfile.ZipFile(name+'.zip', 'w', zipfile.ZIP_DEFLATED)
newzip.write(name+'.txt')
print(newzip.infolist())
newzip.close()
The code runs successfully, but I am facing access denied error while trying to open the zip file.
Compressed (zipped) Folders Error:
Windows cannot open the folder.
Access to the Compressed (zipped) Folder
'C:/Users/XXXXX/Desktop/Files/Position__Global.zip' is denied.
I am not sure what is causing the issue. Could you please check?
My office IT team debugged this:
The issue was due to restrictions on user privileges on my office PC. It occurs when you have user access but the python is being executed as Administrator. Then the file created by the administrator will not be available to be opened by common user.
Most of time, it happened at some application open the file and not closed. Remember to close the opened file in your script, or try to close your application when failed before you close the opened file.
import zipfile
newzip = zipfile.ZipFile('D:/test.zip', 'w', zipfile.ZIP_DEFLATED)
newzip.write('D:/test.txt')
print(newzip.infolist())
# newzip.close()

Which user opens a file in python?

I am working with django and celery. In my celery task, I instantiate a class and that class is responsible for generating and mailing a CSV file.
My problem is I am getting IOError: [Errno 13] Permission denied
when i try to do fp = open(filename, 'w'). But how do I get to know which user of my server is trying to create that file and how can I provide that user with appropriate permissions.I am working on AWS server.
My code for writing files is this:
with open(filename, 'w') as f_pointer:
os.chmod(filename, 777)
myfile = csv.writer(f_pointer)
myfile.writerow(columns)
myfile.writerows(rows)
Thanks
First check the file permission or owner , then use the property permission.
ls -l filename
Another, you should check if this user can create the filename in the directory .
The file is opened by the same user who is running the process. Now if the directory where you are creating the file or file you opening to write to are not writable by the user, then chmod will not work.
You'll have to chose the directory/file that is writable by the user.

Categories

Resources