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:
= file.readlines()
lines 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:
= file.read()
content print(content) # Output: Stampa il contenuto del file CSV
# 13. Conta le Righe in un File
with open("test.txt", "r") as file:
= file.readlines()
lines 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:
= max(file, key=len)
longest_line print(longest_line.strip()) # Output: Riga più lunga
# 15. Scrittura e Lettura di un Dizionario in un File
= {"nome": "Mario", "età": 28, "città": "Roma"}
data with open("data.txt", "w") as file:
file.write(str(data))
with open("data.txt", "r") as file:
= eval(file.read()) # Ricostruisce il dizionario
content print(content) # Output: {'nome': 'Mario', 'età': 28, 'città': 'Roma'}
# 16. Scrittura e Lettura di un File JSON
import json
= {"nome": "Elena", "età": 22, "città": "Torino"}
person
with open("person.json", "w") as file:
file)
json.dump(person,
with open("person.json", "r") as file:
= json.load(file)
data print(data) # Output: {'nome': 'Elena', 'età': 22, 'città': 'Torino'}
# 17. Ricerca e Sostituzione in un File
with open("test.txt", "r") as file:
= file.read()
content
= content.replace("Python", "Java")
content
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:
= f1.readlines()
lines1 = f2.readlines()
lines2
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:
= file.read(100)
bytes_data 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:
= file.readlines()
lines 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:
= file.read()
content print(content) # Output: Print the contents of the CSV file
# 13. Counting Lines in a File
with open("test.txt", "r") as file:
= file.readlines()
lines print(len(lines)) # Output: Number of lines in file
# 14. Find the Longest Line in a File
with open("test.txt", "r") as file:
= max(file, key=len)
longest_line print(longest_line.strip()) # Output: Longest Line
# 15. Writing and Reading a Dictionary in a File
= {"name": "Mario", "age": 28, "city": "Roma"}
data with open("data.txt", "w") as file:
file.write(str(data))
with open("data.txt", "r") as file:
= eval(file.read()) # Rebuild the dictionary
content print(content) # Output: {'name': 'Mario', 'age': 28, 'city': 'Roma'}
# 16. Writing and Reading a JSON File
import json
= {"name": "Elena", "age": 22, "city": "Turin"}
person
with open("person.json", "w") as file:
file)
json.dump(person,
with open("person.json", "r") as file:
= json.load(file)
data print(data) # Output: {'name': 'Elena', 'age': 22, 'city': 'Turin'}
# 17. Search and Replace in a File
with open("test.txt", "r") as file:
= file.read()
content
= content.replace("Python", "Java")
content
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:
= f1.readlines()
lines1 = f2.readlines()
lines2
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:
= file.read(100)
bytes_data 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
Posta un commento