Answer the question
In order to leave comments, you need to log in
How to set paths to standard folders in python?
I am writing a program, and it should create folders in the standard Windows folders, such as loading the desktop, user folder, how to make these paths work on any PC?
Tried like this, got an error:
text = "%USERPROFILE%\Desktop"
chdir(text)
mkdir(voice)
Answer the question
In order to leave comments, you need to log in
If you need to create, read and modify files and folders inside your script, based on the binding to the user's "home" folder, you can do something like this:
from pathlib import Path
my_home_dir = Path.home()
new_folder_name = 'my_new_folder'
new_folder = Path(new_folder_name)
new_folder_full_path = my_home_dir / new_folder
try:
Path.rmdir(new_folder_full_path)
except FileNotFoundError:
pass
print(new_folder_full_path.is_dir())
try:
Path.mkdir(new_folder_full_path)
except FileExistsError:
pass
print(new_folder_full_path.is_dir())
import os
import os.path
text = os.path.join(os.getenv("userprofile"), "Desktop")
os.chdir(text)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question