Lavorare con file

Lavorare con file Lavorare con file.md

Lavorare con file

Versione italiana

Lavorare con i file è un'operazione comune in Python, sia per leggere dati da file esterni sia per salvare risultati. Ecco una spiegazione dettagliata delle operazioni che hai menzionato:


Apertura, lettura e scrittura di file

  1. Apertura di un file:

    • Si usa la funzione open() per aprire un file.
    • Sintassi: open(nome_file, modalità)
    • Modalità comuni:
      • "r": lettura (default).
      • "w": scrittura (sovrascrive il file se esiste).
      • "a": aggiunta (scrive in coda al file).
      • "b": modalità binaria (es. "rb" o "wb").
      • "+": lettura e scrittura (es. "r+").

    Esempio:

    file = open("file.txt", "r")
  2. Lettura di un file:

    • read(): legge l'intero contenuto del file.
    • readline(): legge una riga alla volta.
    • readlines(): legge tutte le righe e le restituisce come una lista.

    Esempio:

    file = open("file.txt", "r") contenuto = file.read() # Legge l'intero file print(contenuto) file.close()
  3. Scrittura di un file:

    • write(): scrive una stringa nel file.
    • writelines(): scrive una lista di stringhe nel file.

    Esempio:

    file = open("file.txt", "w") file.write("Ciao, mondo!") # Scrive nel file file.close()
  4. Chiusura di un file:

    • È importante chiudere il file dopo l'uso per liberare risorse.
    • Si usa il metodo close().

    Esempio:

    file = open("file.txt", "r") contenuto = file.read() file.close()

Gestione dei file con with

  1. Blocco with:

    • È il modo più sicuro per lavorare con i file, poiché chiude automaticamente il file alla fine del blocco.
    • Sintassi: with open(nome_file, modalità) as variabile:

    Esempio:

    with open("file.txt", "r") as file: contenuto = file.read() print(contenuto) # Il file viene chiuso automaticamente qui
  2. Vantaggi di with:

    • Non devi preoccuparti di chiudere manualmente il file.
    • Gestisce automaticamente le eccezioni.

File in formato JSON

  1. Cos'è JSON?

    • JSON (JavaScript Object Notation) è un formato leggero per lo scambio di dati.
    • È molto usato per salvare e leggere dati strutturati.
  2. Lettura di un file JSON:

    • Si usa json.load() per caricare dati da un file JSON.
    • Esempio:
      import json with open("dati.json", "r") as file: dati = json.load(file) # Carica i dati dal file print(dati)
  3. Scrittura di un file JSON:

    • Si usa json.dump() per salvare dati in un file JSON.
    • Esempio:
      import json dati = {"nome": "Mario", "età": 30} with open("dati.json", "w") as file: json.dump(dati, file) # Salva i dati nel file
  4. Formattazione del JSON:

    • Puoi usare il parametro indent per formattare il JSON in modo leggibile.
    • Esempio:
      import json dati = {"nome": "Mario", "età": 30} with open("dati.json", "w") as file: json.dump(dati, file, indent=4) # Formatta il JSON

Esempi completi

  1. Lettura e scrittura di un file di testo:

    # Scrittura with open("file.txt", "w") as file: file.write("Ciao, mondo!\n") file.write("Questo è un file di testo.") # Lettura with open("file.txt", "r") as file: contenuto = file.read() print(contenuto)
  2. Lettura e scrittura di un file JSON:

    import json # Dati da salvare dati = { "nome": "Mario", "età": 30, "città": "Roma" } # Scrittura with open("dati.json", "w") as file: json.dump(dati, file, indent=4) # Lettura with open("dati.json", "r") as file: dati_caricati = json.load(file) print(dati_caricati)

    English version

    Working with files

Working with files is a common operation in Python, both for reading data from external files and for saving results. Here is a detailed explanation of the operations you mentioned:


Opening, reading and writing files

  1. Opening a file:
  • Use the open() function to open a file.
  • Syntax: open(filename, mode)
  • Common modes:
  • "r": read (default).
  • "w": write (overwrites the file if it exists).
  • "a": append (writes to the end of the file).
  • "b": binary mode (e.g. "rb" or "wb").
  • "+": read and write (e.g. "r+").

Example:

file = open("file.txt", "r")
  1. Reading a file:
  • read(): Reads the entire contents of the file.
  • readline(): Reads one line at a time.
  • readlines(): Reads all the lines and returns them as a list.

Example:

file = open("file.txt", "r") content = file.read() # Reads the entire file print(content) file.close()
  1. Writing a file:
  • write(): Writes a string to the file.
  • writelines(): Writes a list of strings to the file.

Example:

file = open("file.txt", "w") file.write("Hello, world!") # Write to file file.close()
  1. Closing a file:
  • It is important to close the file after use to free up resources.
  • Use the close() method.

Example:

file = open("file.txt", "r") content = file.read() file.close()

File handling with with

  1. with block:
  • It is the safest way to work with files, as it automatically closes the file at the end of the block.
  • Syntax: with open(filename, mode) as variable:

Example:

with open("file.txt", "r") as file: content = file.read() print(content) # The file is automatically closed here
  1. Advantages of with:
  • You don't have to worry about manually closing the file.
  • It automatically handles exceptions.

JSON format files

  1. What is JSON?
  • JSON (JavaScript Object Notation) is a lightweight format for data exchange.
  • It is widely used for saving and reading structured data.
  1. Reading a JSON file:
  • Use json.load() to load data from a JSON file.
  • Example:
import json with open("data.json", "r") as file: data = json.load(file) # Load data from file print(data)
  1. Writing a JSON file:
  • Use json.dump() to save data to a JSON file.
  • Example:
import json data = {"name": "Mario", "age": 30} with open("data.json", "w") as file: json.dump(data, file) # Save data to file
  1. Formatting JSON:
  • You can use the indent parameter to format the JSON in a readable way.
  • Example:
import json data = {"name": "Mario", "age": 30} with open("data.json", "w") as file: json.dump(data, file, indent=4) # Format the JSON

Complete examples

  1. Reading and writing a text file:
# Writing with open("file.txt", "w") as file: file.write("Hello, world!\n") file.write("This is a text file.") # Reading with open("file.txt", "r") as file: content = file.read() print(content)
  1. Reading and writing a JSON file:
import json # Data to save data = { "name": "Mario", "age": 30, "city": "Rome" } # Write with open("dati.json", "w") as file: json.dump(dati, file, indent=4) # Read with open("dati.json", "r") as file: dati_caricati = json.load(file) print(dati_caricati)

Commenti