Get python Documents directory automatically

Asked

Viewed 309 times

0

I need to automatically get the address of the document folder of any Windows with Python.

Currently in my script determined as shown in the variable main_folder, but whenever I change PC I have to change this address. Below is also one of the uses of this variable in my script.

Creating directories and subdirectories. If anyone knows any other method, I will be very grateful.

import arcpy
main_folder = r"C:\Users\Edeson Bizerril\Documents\myEBpy_Files"

# EXEMPLO DE USO
# Determinando diretório
input_folder = main_folder + "\Input\\"
input_folder_SRTM = self.input_folder + r"SRTMs\\"

create_folder(input_folder)

create_folder(input_folder_SRTM)

# Método para criação de diretórios
def create_folder(path):
    if not os.path.isdir(path):
        os.makedirs(path)

Unfortunately I need to determine the reference folder in my work, but I would like Python to automatically identify and return me exactly the same result in the variable main_folder.

  • Dude, I couldn’t quite figure out what you want. It’s like putting an example of output or even a step by step with start, middle and end?

  • I work with Arcgis and python, so I need to inform arcgis the main work address. The way you were informed works, because I inform him by associating this variable. But whenever I change the pc I need to change the username. understand? But I’ll see if I can improve this question

2 answers

4


In the standard python library there is the module os.path which has several methods to assist in handling operating system directories.

For you to get the user’s initial (home) directory you can use the function expanduser.

from os import path


main_folder = path.join(path.expanduser("~"), "Documents/myEBpy_Files")

In Windows will return: C:\Users\Usuario\Documents\myEBpy_Files

  • 3

    Perfect - I didn’t know expanduser worked on Windows either. I think you can do it in one call, you can’t do it? path.expanduser("~/Documents/myEBpy_Files") - the ~ automatically already turns the path to the user folder.

  • 1

    I thought about it, but in the test I performed there was no "/" treatment, so I used the join.

1

With the new directory manipulation API, pathlib, you can get the user directory from:

from pathlib import Path
home = Path.home()

This will return an object referring to the directory home user in question. To access the directory "Documents", just do:

documents = home / 'Documentos'

The division operator, in this case, is overloaded to change the directory, to follow the same syntax of the operating system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.