Using variable in the chdir function (OS module)

0

Is it possible to use the data given in a variable in some other function other than the chdir () of the Python OS module?

I noticed that it is not possible to use variables in directory exchange using this method. Was there another of the kind? (may be from another module inclusive).

The idea would look like this:

import os

def mudardir():
    a = 'Python'
    os.chdir('C:/Users/','a','diretoriob')

 mudardir()

As I do not know what the user name is and the Windows variable % userprofile% is not supported by the method, so I thought I'd set it before and then use it inside the function!

I am grateful for the attention of all!

    
asked by anonymous 28.01.2018 / 05:43

1 answer

0

To recover the user directory you can use the % / a>, example:

from os.path import expanduser
user_dir = expanduser("~")
print(user_dir)

The output in Windows will be similar:

'C:\Users\Thon'

TheoutputinLinuxwillbesimilar:

/home/wmsouza
  

Youcanseeitworkingat repl.it .

Or you can use the os.path.expanduser library available at Python 3.5 + .

from pathlib import Path
user_dir = str(Path.home())
print(user_dir)
  

You can see it working at repl.it .

Knowing this, just add a parameter to your method:

import os
from os.path import expanduser

def mudardir(diretorio):
    user_dir = expanduser("~")
    os.chdir(user_dir + diretorio)

# Em meu computador seria algo assim
# /home/wmsouza/Python
mudardir('/Python')
# /home/wmsouza/Python/Projeto_A
mudardir('/Python/Projeto_A')
# /home/wmsouza/Python/Projeto_B
mudardir('/Python/Projeto_B')
    
28.01.2018 / 07:03