Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- class Libreria():
- def aggiungi(self, fnome):
- while True:
- titolo = input("\nTitolo: ('.' per interrompere)\n").title()
- if titolo == '.':
- break
- autore = input("\nAutore: \n").title()
- ''' Scrittura sul file '''
- with open(fnome, "a") as file:
- file.write(f"{titolo} - {autore}\n")
- print(f"\nHai appena aggiunto {titolo} di {autore}.\n")
- return 0
- def rimuovi(self, fnome):
- ''' Chiediamo all'utente il numero della riga da cancellare, ma si tratta di un
- indice falsato (la conta delle righe inizia da 0). '''
- i = int(input("\nIndice da rimuovere:\n"))
- ''' Sfruttiamo il metodo readlines() per raggruppare il contenuto
- del file in una lista. I metodi delle liste vengono in nostro soccorso. '''
- with open(fnome, "r+") as file:
- righe = file.readlines()
- ''' Decrementiamo l'indice inserito dall'utente per la ragione vista sopra. '''
- i -= 1
- for riga in righe:
- if i == righe.index(riga):
- print(f"\nHai cancellato {riga}")
- righe.pop(i)
- ''' Stampiamo file.readlines() sul file. '''
- ''' Riaprire il file in modalità 'w' ci consente di resettarlo. '''
- with open(fnome, "w") as file:
- file.writelines(righe)
- return 0
- def mostra(self, fnome):
- ''' Contatore di righe '''
- i = 0
- ''' Lettura del file '''
- with open(fnome, "r") as file:
- print("\n")
- for riga in file:
- ''' anche qui l'indice è falsato; lo si incrementa '''
- i += 1
- print(f"[{i}] {riga}")
- return 0
- def canc_file(self, fnome):
- s_n = input("\nSicuro/a di voler cancellare il file [s/n]?\n")
- if s_n == 's':
- os.remove(fnome)
- return 0
- elif s_n == 'n':
- return 1
- else:
- print("\nScelta non valida.\n")
- return 1
- def cerca(self, fnome):
- titolo = input("\nTitolo da cercare:")
- if titolo in fnome:
- return 1
- else:
- return 0
- def main():
- libr = Libreria()
- fnome = "libri.txt"
- if not os.path.exists(fnome):
- print("\nFile non trovato.\n")
- while True:
- try:
- scelta = int(input("\nLIBRERIA DI TESTO\n\n1. Aggiungi Libro\n2. Rimuovi Libro\n3. Mostra Libri\n4. Cancella File\n5. Cerca\n6. Esci\n"))
- if scelta == 1:
- libr.aggiungi(fnome)
- elif scelta == 2:
- libr.rimuovi(fnome)
- elif scelta == 3:
- libr.mostra(fnome)
- elif scelta == 4:
- libr.canc_file(fnome)
- elif scelta == 5:
- libr.cerca(fnome)
- elif scelta == 6:
- print("\nArrivederci!")
- break
- else:
- print("\nDevi mettere un numero tra 1 e 5.")
- except ValueError:
- print("\nNon puoi inserire lettere.")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment