Checking and creating python directories

Asked

Viewed 5,711 times

5

Hello,

I am creating a code that should check if a folder exists, if it does not exist the code should create it and then proceed, otherwise it just goes with the flow.

I tried with If and While but I was not successful. Most of the time it creates the folder I want but returns me the error "Could not create an existing folder". For this to happen there must be a loop that I’m not able to identify, can help me?

Follow the two forms I tried below:

MODE 1:

if username and password != None:

    while os.path.exists('C:\ Backup') == False:

        makedirs("C:\ Backup\ ")

        if os.path.exists('C:\ Backup') == True:
            break

else:
    print "nao foi possivel logar"

            #for ip in radius:

            #gravar = open(ip+".txt", "w")
            #gravar.write("Configuração")
            #gravar.close()

MODE 2:

if username and password != None:

    if pass os.path.exists('C:\ Backup') == False:

        makedirs("C:\ Backup\ ")

        else:

            for ip in radius:

            gravar = open(ip+".txt", "w")
            gravar.write("Configuração")
            gravar.close()

else:
    print "nao foi possivel logar"

PS: Maybe it’s something simple that I couldn’t identify, I don’t have much experience with programming but I’m trying to improve. So, i’m Sorry.

Thank you!

1 answer

4


Do so:

import os.path

# nao tenho bem a certeza se e isto que quer, nao sera: if username == 'USERNAME CORRETO' and password == 'PASSWORD CORRETA': ?
if username != None and password != None:
    pasta = 'C:\Backup'
    if os.path.isdir(pasta): # vemos de este diretorio ja existe
        print ('Ja existe uma pasta com esse nome!')
    else:
        os.mkdir(pasta) # aqui criamos a pasta caso nao exista
        print ('Pasta criada com sucesso!')

    # prosseguir com o codigo aqui, nesta linha onde esta o cardinal (hash)

else:
    print 'nao foi possivel logar'
  • Thanks Miguel, you helped me a lot!

  • You’re welcome @Cristhianmiguel. I’m glad you decided

Browser other questions tagged

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