Access Denied to zipfile created using python - 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()

Related

Python Folder Permission writing issue

Could someone please give me some guidance. I am pretty fresh with python.
All I am wanting to do is download zip files from web addresses and save them to a folder.
The same process happens every month so I am trying to automate it.
I have sucessfully download the zip file to a folder of my choice, but when I get python to create the folder I get permission errors. I have read online I can use os.chmod and grant permissions but I cannot figure out how to structure it/ write it so it works
This is what I have so far.
import requests, zipfile, io
import os
from datetime import datetime
d = datetime.today().strftime('%b%y') #'Dec20'
newpath = 'L:/Support/Data_load/NativeTitle/{}'.format(d)
if not os.path.exists(newpath):
os.makedirs(newpath)
os.chmod(newpath , 0o0777)
#chmod -R 777 'L:/Support/Data_load/NativeTitle/{}'.format(d)
print('Folder created in L:\Support\Data_load\NativeTitle')
print('Beginning file download with urllib2...')
url = 'http://www.nntt.gov.au/GeoDocs//ESRI/NTDA_Schedule_Nat_shp.zip'
urllib.urlretrieve(url, newpath)
IOError: [Errno 13] Permission denied: 'L:/Support/Data_load/NativeTitle/Oct21'

Save xlsx file in Desktop using Django

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")

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.

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.

Python: PermissionError while writing a file to windows dir

When i want to open a file in C:\ (windows dir.) this error shows up:
PermissionError: [Errno 13] Permission denied: 'C:\h.txt'
What should i do?
I know this question has been asked several times but i can't find solution!
code:
f=open ('C:\\h.txt','w')
f.write ('python')
f.close
I am not on win machine, but give this a try, you can manage permissions using these commands
Try to open your file using os.fdopen
import os
with os.fdopen(os.open('file.txt', os.O_WRONLY | os.O_CREAT, 0600), 'w') as f:
f.write(...)
UPDATE
import os
is_accessible = os.access("C:\\temp\\python",os.F_OK) #Check if you have access, this should be a path
if is_accessible == False: #If you don't, create the path
os.makedirs("C:\\temp\\python")
os.chdir("C:\\temp\\python") # Check now if the path exist
f = os.open( "p.txt", os.O_RDWR|os.O_CREAT ) #Create the file
os.write(f, b"This is a test \n") #Try to write
os.close(f)
I'm not on a Windows machine but perhaps you should try and create this file in the directory c:\Temp.
Likewise make sure you've not got Notepad etc with that file open.

Categories

Resources