I’m new to Python and I am encountering the following error:
Traceback (most recent call last):
File "home_dir_conf.py", line 19, in <module>
with open(conf_dir_path, "w") as msg_file:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\svaleriev\\.python-course-home-dir-conf'
Here’s the code I’m currently using: https://pastebin.com/ujgkWsXh
import os
home_dir = os.path.expanduser("~")
conf_dir = "python-course-home-dir-conf"
conf_dir_path = os.path.join(home_dir, conf_dir)
os.makedirs(conf_dir_path, exist_ok=True)
conf_file_name = "message.conf"
conf_file_path = os.path.join(conf_dir_path, conf_file_name)
print(conf_dir_path)
DEFAULT_MESSAGE = "Change me!"
if os.path.exists(conf_file_path):
with open(conf_file_path) as msg_file:
message = msg_file.read()
print(f"Configured message: {message}")
else:
with open(conf_dir_path, "w") as msg_file:
msg_file.write(DEFAULT_MESSAGE)
print(f"Message set!")
Can someone provide guidance on what is causing this error and how to address it?
>Solution :
You must replace
else:
with open(conf_dir_path, "w") as msg_file:
msg_file.write(DEFAULT_MESSAGE)
print(f"Message set!")
by
else:
with open(conf_file_path, "w") as msg_file:
msg_file.write(DEFAULT_MESSAGE)
print(f"Message set!")