Es. Python tutorial - Lavorare con i file 2

Es. Python tutorial - Lavorare con i file 2 Es. Python tutorial - Lavorare con i file 2

Es. Python tutorial - Lavorare con i file 2

Versione italiana

Esercizi

11. Lettura di un File con .readlines()

Leggi tutte le righe del file test.txt usando il metodo .readlines() e stampale come una lista.

12. Creazione e Lettura di un File CSV

Crea un file data.csv e scrivi dentro tre righe di dati nel formato: "Nome,Età,Città". Poi leggi e stampa il contenuto.

13. Conta le Righe in un File

Scrivi un programma che apra test.txt e conti il numero di righe presenti.

14. Trova la Riga più Lunga in un File

Leggi test.txt e trova la riga con il maggior numero di caratteri.

15. Scrittura e Lettura di un Dizionario in un File

Crea un dizionario Python con alcune chiavi e valori e salvalo in data.txt. Poi rileggilo e ricostruisci il dizionario.

16. Scrittura e Lettura di un File JSON

Crea un dizionario con dati su una persona e salvalo in un file person.json. Poi rileggilo e stampalo.

17. Ricerca e Sostituzione in un File

Scrivi un programma che apra test.txt, sostituisca ogni occorrenza della parola "Python" con "Java", e salvi il file aggiornato.

18. Confronto tra Due File

Scrivi un programma che confronti due file file1.txt e file2.txt e stampi le differenze riga per riga.

19. Lettura di un File Binario

Apri un file immagine .jpg in modalità binaria, leggi i primi 100 byte e stampali.

20. Scrittura di un File Log

Crea un programma che scriva un log delle operazioni eseguite in un file log.txt aggiungendo una nuova riga ogni volta che il programma viene eseguito.


Soluzioni

# 11. Lettura di un File con `.readlines()`
with open("test.txt", "r") as file:
    lines = file.readlines()
print(lines)  # Output: Lista di righe del file

# 12. Creazione e Lettura di un File CSV
with open("data.csv", "w") as file:
    file.write("Nome,Età,Città\nAlice,30,Roma\nBob,25,Milano\nCharlie,35,Napoli")

with open("data.csv", "r") as file:
    content = file.read()
print(content)  # Output: Stampa il contenuto del file CSV

# 13. Conta le Righe in un File
with open("test.txt", "r") as file:
    lines = file.readlines()
print(len(lines))  # Output: Numero di righe nel file

# 14. Trova la Riga più Lunga in un File
with open("test.txt", "r") as file:
    longest_line = max(file, key=len)
print(longest_line.strip())  # Output: Riga più lunga

# 15. Scrittura e Lettura di un Dizionario in un File
data = {"nome": "Mario", "età": 28, "città": "Roma"}
with open("data.txt", "w") as file:
    file.write(str(data))

with open("data.txt", "r") as file:
    content = eval(file.read())  # Ricostruisce il dizionario
print(content)  # Output: {'nome': 'Mario', 'età': 28, 'città': 'Roma'}

# 16. Scrittura e Lettura di un File JSON
import json
person = {"nome": "Elena", "età": 22, "città": "Torino"}

with open("person.json", "w") as file:
    json.dump(person, file)

with open("person.json", "r") as file:
    data = json.load(file)
print(data)  # Output: {'nome': 'Elena', 'età': 22, 'città': 'Torino'}

# 17. Ricerca e Sostituzione in un File
with open("test.txt", "r") as file:
    content = file.read()

content = content.replace("Python", "Java")

with open("test.txt", "w") as file:
    file.write(content)

# 18. Confronto tra Due File
with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2:
    lines1 = f1.readlines()
    lines2 = f2.readlines()

for i, (line1, line2) in enumerate(zip(lines1, lines2), start=1):
    if line1 != line2:
        print(f"Differenza alla riga {i}:")
        print(f"File1: {line1.strip()}")
        print(f"File2: {line2.strip()}")

# 19. Lettura di un File Binario
with open("image.jpg", "rb") as file:
    bytes_data = file.read(100)
print(bytes_data)  # Output: Primi 100 byte del file

# 20. Scrittura di un File Log
from datetime import datetime

with open("log.txt", "a") as file:
    file.write(f"{datetime.now()}: Programma eseguito\n")

English version

Exercises

11. Reading a File with .readlines()

Read all the lines of the file test.txt using the .readlines() method and print them as a list.

12. Creating and Reading a CSV File

Create a file data.csv and write three lines of data in the format: "Name,Age,City". Then read and print the content.

13. Counting Lines in a File

Write a program that opens test.txt and counts the number of lines in it.

14. Finding the Longest Line in a File

Read test.txt and find the line with the most characters.

15. Writing and Reading a Dictionary in a File

Create a Python dictionary with some keys and values ​​and save it in data.txt. Then read it back and rebuild the dictionary.

16. Writing and Reading a JSON File

Create a dictionary with data about a person and save it in a file person.json. Then read it back and print it.

17. Search and Replace in a File

Write a program that opens test.txt, replaces every occurrence of the word "Python" with "Java", and saves the updated file.

18. Comparing Two Files

Write a program that compares two files file1.txt and file2.txt and prints the differences line by line.

19. Reading a Binary File

Open a .jpg image file in binary mode, read the first 100 bytes and print them.

20. Writing a Log File

Create a program that writes a log of the operations performed to a file log.txt adding a new line each time the program is executed.


Solutions

# 11. Reading a File with `.readlines()`
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines) # Output: List of lines in the file

# 12. Creating and Reading a CSV File
with open("data.csv", "w") as file:
file.write("Name,Age,City\nAlice,30,Rome\nBob,25,Milan\nCharlie,35,Naples")

with open("data.csv", "r") as file:
content = file.read()
print(content) # Output: Print the contents of the CSV file

# 13. Counting Lines in a File
with open("test.txt", "r") as file:
lines = file.readlines()
print(len(lines)) # Output: Number of lines in file

# 14. Find the Longest Line in a File
with open("test.txt", "r") as file:
longest_line = max(file, key=len)
print(longest_line.strip()) # Output: Longest Line

# 15. Writing and Reading a Dictionary in a File
data = {"name": "Mario", "age": 28, "city": "Roma"}
with open("data.txt", "w") as file:
file.write(str(data))

with open("data.txt", "r") as file:
content = eval(file.read()) # Rebuild the dictionary
print(content) # Output: {'name': 'Mario', 'age': 28, 'city': 'Roma'}

# 16. Writing and Reading a JSON File
import json
person = {"name": "Elena", "age": 22, "city": "Turin"}

with open("person.json", "w") as file:
 json.dump(person, file)

with open("person.json", "r") as file:
 data = json.load(file)
print(data) # Output: {'name': 'Elena', 'age': 22, 'city': 'Turin'}

# 17. Search and Replace in a File
with open("test.txt", "r") as file:
 content = file.read()

content = content.replace("Python", "Java")

with open("test.txt", "w") as file:
 file.write(content)

# 18. Comparing Two Files
with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2:
 lines1 = f1.readlines()
 lines2 = f2.readlines()

for i, (line1, line2) in enumerate(zip(lines1, lines2), start=1):
 if line1 != line2:
 print(f"Difference at line {i}:")
 print(f"File1: {line1.strip()}")
 print(f"File2: {line2.strip()}")

#19. Reading a Binary File
with open("image.jpg", "rb") as file:
 bytes_data = file.read(100)
print(bytes_data) # Output: First 100 bytes of the file

# 20. Writing a Log File
from datetime import datetime

with open("log.txt", "a") as file:
 file.write(f"{datetime.now()}: Program executed\n")

Commenti