L
L
Lumus2022-04-17 08:09:20
Python
Lumus, 2022-04-17 08:09:20

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)

what can they be replaced with, are there any universal ways for python?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alan Gibizov, 2022-04-17
@phaggi

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

Note in brackets
Следует отметить, что существуют сторонние библиотеки, которые не понимают такие пути. Для таких библиотек приходится получать строчное представление пути.

A
alekssamos, 2022-04-17
@alekssamos

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 question

Ask a Question

731 491 924 answers to any question