Check existence of Python file with function

Asked

Viewed 357 times

1

I searched all the repositories corresponding to my doubt here, but all are very direct when creating and reading part of files in Python, but I saw nothing related using function.

Function to create file and check if file exists

def cria_arq(nome_arquivo):
# para criar arquivo usando path lib
if not os.path.exists('nome_arquivo'):
    Path(f'{nome_arquivo}.txt').touch()
else:
    print('Já existe um arquivo com este nome!!')

Menu to capture file name

def menu_arquivos():
# clear()
title('Navegando pelo Menu ARQUIVOS')
print('Escolha sua opção: ')
op = int(input('''
    [1] - Criar arquivos
    [2] - Ler arquivos
    [3] - Editar arquivos
    [4] - Apagar arquivos
    [0] - Retornar/Sair

    Opção: '''))

if op == 0:
    menu()
elif op == 1:
    # cria_arq(str(input('Nome do arquivo: ')))
    j = 'S'
    while j == 'S':
        cria_arq(str(input('Nome do arquivo: ')))
        j = str(input('Deseja criar um novo arquivo? [S/N]')).upper()
    menu_arquivos()

Based on the codes shown above I wanted that when picking the user input the name of the file he wants to create, and if the name he gave input was equal to an existing one, the function would return the file already exists and return to the loop in the menu to know if the user wants to create a new file or not.

I tried to change the function line cria_arq for these 3 forms, but without success:

if not os.path.exists(f'{nome_arquivo}'):
if not os.path.exists('nome_arquivo'):
if not os.path.exists(nome_arquivo):

I am a beginner in the language and I am creating a kind of Explorer (only with processing of text files). The code is still in development, gradually I improve as I learn different things.

From now on, I appreciate all your help!!!

1 answer

2


Hello, all right?

So the problem lies in your role cria_arq, you have as argument nome_arquivo however you are checking on if string filename and not the variable itself.

See that you have to pass the full file name with its extension, otherwise it will return false.

For example, suppose I have a file with a name file.txt.

os.path.exist('file') # Retorna Falso
os.path.exist('file.txt') # Retorna True

Your role should look like this (just suggestion)

def cria_arq(nome_arquivo):
    if not os.path.exists(nome_arquivo):
        Path(nome_arquivo).touch()
    else:
        print('Já existe um arquivo com este nome!!')

If you wanted to write only the file name and the extension separately. In this case if the person does not type the extension, by default the file if it does not exist will have the extension txt.

def cria_arq(nome_arquivo, extensao='txt'):
    file = '.'.join([nome_arquivo, extensao])
    if not os.path.exists(file):
        Path(file).touch()
    else:
        print('Já existe um arquivo com este nome!!')

Example:

cria_arq('arquivo') # cria a função 'arquivo.txt'
cria_arq('arquivo', 'csv') # cria a função 'arquivo.csv'
  • Octavian, Thank you for your help!! I understood what you explained, but I am still stuck in the question of having to type the '.txt' along with the name to create the file, because if at the time I call the function I do not put the extension, it creates a null file, I need him to be a .txt. Is there any way to do that? But your help was of great value, noting that I can put the user to inform the file format. Thank you!!!

  • Exactly Adriel, if you do not pass the name along with the extension it will create a null file (no extension). It is possible, yes see the edited response and see if it meets your expectations.

  • Attended too much, solved the problem completely!! Thank you for the help and patience!! Thank you

Browser other questions tagged

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