Checking and creating folders in python

4

Hello,

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

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

Here are the two ways 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 could not identify, I do not have much programming experience but I'm trying to improve. So, I'm sorry.

Thank you!

    
asked by anonymous 09.07.2016 / 05:48

1 answer

2

Do this:

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'
    
09.07.2016 / 13:20