Check if there is a file if there is a PYTHON report.

4

Verify that the folder no longer exists, if it exists, it should print a message to the user indicating.

I got stuck without knowing how to check something related to this:

os.listdir()
os.mkdir (input('Insira o nome:'))
if os.path.exists ('Users\Akros\Desktop\TESTE') == True:
  print ('Ja existe um arquivo com esse nome!')
else:
  print ("Criado com sucesso!")

The error that appears is:

File "C:\Users\Akros\Desktop\TESTE\OS.py", line 21, in sys_calls
os.mkdir (input('Insira o nome:'))
FileExistsError: [WinError 183] Não é possível criar um arquivo já existente: 'AKROS'

I have already used os.path.isdir / os.path.isfile / os.path.lexists.

This is a requirement for an exercise I am doing at the federal institute, if you link in this case request that if a folder is created or deleted that already exists or does not exist warn the user. But I can not figure out which command or the logic of how to do this, it will not pro "print" the error message will appear.

    
asked by anonymous 05.06.2016 / 07:16

1 answer

3

The problem is that you are trying to create the directory right on this line:

os.mkdir (input('Insira o nome:'))

And it throws the exception (this warning / error) because it should already exist. You should first see if it exists before you create it, like this:

import os.path

diretorio = input('Insira o nome:')
if os.path.isdir(diretorio): # vemos de este diretorio já existe
  print ('Ja existe um arquivo com esse nome!')
else:
  os.mkdir(diretorio) # aqui criamos o diretorio
  print ("Criado com sucesso!")

Note that all the methods you used are for different things, in the end it's true that everyone checks for something. More:

if os.path.isdir(path):  # Verifica se e diretorio
   ...

if os.path.isfile(path): # Verifica se e ficheiro
   ...

if s.path.exists(path): # verifica se existe, seja ficheiro (arquivo), ou diretorio
   ...

You must adjust one of these to suit you. Another thing, by the warning that gives ('There is a file with that name!'), I see that you may be trying to create a file and not a directory, if it is the case change these two lines:

if os.path.isdir(diretorio):
...
os.mkdir(diretorio)

By

if os.path.isfile(diretorio):
...
ficheiro = open(diretorio, "w") # criamos/abrimos o ficheiro
#.... .... ... operacoes no ficheiro
ficheiro.close()
    
05.06.2016 / 10:05