Jul 1, 2024
names = [] # Empty list
for _ in range(3):
name = input("What's your name?")
names.append(name)
for name in sorted(names):
print(f"Hello, {name}")
open
function with mode 'w' (write).
with open("names.txt", "w") as file:
name = input("What's your name?")
file.write(name + "\n") # Ensuring new line
with
statement to handle file opening and closing automatically.
with open("names.txt", "a") as file:
name = input("What's your name?")
file.write(f"{name}\n")
readlines()
to read all lines at once.
with open("names.txt") as file:
lines = file.readlines()
for line in lines:
print(f"Hello, {line.strip()}") # Stripping new lines
with open("names.txt") as file:
for line in file:
print(f"Hello, {line.strip()}")
names = []
with open("names.txt") as file:
for line in file:
names.append(line.strip())
for name in sorted(names):
print(f"Hello, {name}")
reverse=True
parameter in sorted function.name,house
Hermione,Gryffindor
Harry,Gryffindor
Ron,Gryffindor
Draco,Slytherin
csv.reader
for simple parsing and csv.DictReader
for column keys.
import csv
with open("students.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['name']} is in {row['house']}")
csv.writer
with field names.
import csv
name = input("What's your name?")
house = input("What's your house?")
with open("students.csv", "a") as file:
writer = csv.writer(file)
writer.writerow([name, house])
sorted(students, key=lambda student: student['name'])
with open("students.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['name']} is from {row['home']}")
from PIL import Image
images = []
for arg in sys.argv[1:]:
image = Image.open(arg)
images.append(image)
images[0].save("animation.gif", save_all=True, append_images=images[1:], loop=0)
This concludes the lecture on file I/O and handling different file types in Python.