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!!!
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!!!
– Adriel Gama
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.
– Octávio Santana
Attended too much, solved the problem completely!! Thank you for the help and patience!! Thank you
– Adriel Gama