Separate the result that appears in os.getcwd () to be able to display only the c: \

0
  

Make a program that displays the current directory (of which you are saving your programs), the disk drive used, the system user name, and the current folder. Consider the example below. Tip use the split function.

Diretorio Atual = C:\Users\monte\PycharmProjects\Aula3
Unidade do Disco = C:
Nome do Usuario = monte
Pasta Atual = Aula3

I tried to use split and the program did not accept

import os
os.getcwd()
os.getlogin()
lista = []
print(os.getcwd())
print(os.getlogin())
lista.append(os.getcwd()) #variável colocada na lista
    
asked by anonymous 05.10.2018 / 20:06

3 answers

1

Use the functions of os.path !

Assuming you have a d variable with the directory you want (you can use os.getcwd() to get the current directory, but in the example below I'll use the same directory as you've exemplified, to illustrate):

>>> # d = os.getcwd()
>>> d = r'C:\Users\monte\PycharmProjects\Aula3'

To get the drive, use os.path.splitdrive

>>> drive, resto = os.path.splitdrive(d)
>>> print(drive)
C:

To get the current folder, use os.path.basename :

>>> pasta = os.path.basename(d)
>>> print(pasta)
Aula3

See more at os.path documentation here .

    
05.10.2018 / 23:23
0

Using the split function as stated above, I suggest the following workaround:

Consider the following directory as an example:

d = r"C:\Users\monte\PycharmProjects\Aula3"
# OU 
d = "C:\Users\monte\PycharmProjects\Aula3"

Note that in the second case it was placed against double bars \ . This is necessary for Python to recognize the counter bar \ as a character.

The split function goes on:

d_list = d.split("\")
print(d_list)
['C:', 'Users', 'monte', 'PycharmProjects', 'Aula3']

Note that this way we already have all the desired fields separated. Now just take the fields of interest:

Unidade_do_Disco = d_list[0]
Nome_do_Usuario = d_list[2]
Pasta_Atual = d_list[-1]

One final note: When calling the split function with no parameters, the default is to separate the string with whitespace. When passing the parameter, the string is separated using the parameter passed as a criterion.

    
06.10.2018 / 02:28
0

Make a program that displays the current directory (of which you are saving your programs), the disk drive used, the system user name, and the current folder. Consider the example below. Tip use the split function.

Current Directory = C: \ Users \ mount \ PycharmProjects \ Aula3

Disk Drive = C:

User Name = mount

Current Folder = Class3

import os
os.getcwd()
os.getlogin()
d = os.getcwd()
lista = []
print('Diretorio Atual:', os.getcwd())
print('Usuario:', os.getlogin())
lista.append(os.getcwd())
pasta_atual = os.path.basename(d)
lista = ''.join(lista)
lista.split()
print('Unidade de Disco:',lista[0:2])
print('Pasta Atual: ',pasta_atual)
    
08.10.2018 / 21:17