'PermissionError when attempting to open directory with zipfile and pathlib modules
I'm trying to create a zip file using pathlib
, but it's giving me a permission error. Look at the code:
from pathlib import Path
from zipfile import *
import os
from datetime import datetime
time = str(datetime.now())
day = int(time.split(' ')[0].split('-')[2])
month = int(time.split(' ')[0].split('-')[1])
year = int(time.split(' ')[0].split('-')[0])
hour = int(time.split(' ')[1].split(':')[0])
minute = int(time.split(' ')[1].split(':')[1])
filename = f"ilhadodede{day:02d}{month:02d}{year:04d}-{hour:02d}-{minute:02d}.zip"
print(f"{day}/{month}/{year} {hour}:{minute}")
zipped = ZipFile(filename, "w", ZIP_DEFLATED)
print(Path(Path("world") / file))
for root, dirs, files in os.walk("world"):
for file in files:
zipped.write(os.path.join(root, file))
for f in zipped.infolist():
print(f.filename)
This is the error:
Traceback (most recent call last):
File "C:/Users/dyeff/Documents/Server Ilha do Dedé/universal_backup.py", line 20, in <module>
zipped.write(os.path.join(root, file))
File "C:\Users\dyeff\AppData\Local\Programs\Python\Python38\lib\zipfile.py", line 1776, in write
shutil.copyfileobj(src, dest, 1024*8)
File "C:\Users\dyeff\AppData\Local\Programs\Python\Python38\lib\shutil.py", line 202, in copyfileobj
buf = fsrc_read(length)
PermissionError: [Errno 13] Permission denied
This is the line that is throwing the error:
zipped.write(os.path.join(root, file))
Solution 1:[1]
My problem was a file called session.lock
.
I made an if statement to ignore that file and the error "flew away".
It is a file from minecraft world files (this program is to backup a world automatically when I close my server) that stores the datetime from the last time the player entered the server, without that file (this file is for backup matters, so anything related to it is being treated in my own program right now) the game creates it automatically.
Solution 2:[2]
Errors like this
PermissionError: [Errno 13] Permission denied
are a result of due to lack of permission to write/read
from that directory.
To confirm that this is the cause of the error, you can try to create and save a file at that directory in which this command zipped.write(os.path.join(root, file))
would output to. If it's the case then you can look up on how to change directory permissions for the Operating System you are using, see here for Linux
.
If you are using an IDE
, you can try to open that in administrative mode and this will give running scripts full privilege to perform write
operations.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dyefferson Azevedo |
Solution 2 | AzyCrw4282 |