Another YouTube video for Python – this time, about reading and writing to files. It is a bit interesting, if these are your first steps with Python, for me it was a nice reminder of how the “things” used to be done.
Starting with video here:
After watching the video, you may take a look at some of the code, that I have used:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from collections import namedtuple Task = namedtuple("Task", "task_id title urgency") with open ("tasks.txt") as file: lines = file.readlines() updated_lines = [f'#{row}: {line.strip()}' for row, line in enumerate(lines, start = 1)] print(updated_lines) expected_output = [ '#1: 1001, Homework, 5', '#2: 1002, Vitoshacademy, 66', '#3: 1003, Herecomesthecode, 45' ] assert updated_lines == expected_output |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
data = """1001, VitoshAcademy, 55 1002, V2, 35 1003, V3, 39912""" with open("tasks_new.txt", "w") as file: print("File:", file) result = file.write(data) print(f"Writing result:{result}") list_data = [ '11001, Vitoshacademy, 5', '11002, .com, 123', '11003, Ale!, 1234' ] with open("tasks_list_write_2.txt", "w") as file: file.write("\n".join(list_data)) |
1 2 |
with open("tasks_list_write_2.txt", "a") as file: file.write("\n".join(list_data)) |
And this is a whole summary of the file modes:
That’s all, enjoy your day!