Python – Reading and Writing Files – With YouTube Video

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.

Random picture from the Bulgarian seaside.

Starting with video here:

Reading And Writing Files with Python

After watching the video, you may take a look at some of the code, that I have used:

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
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))
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:

Pic from “Python – How to” by Yong Cui. Get 40% discout with the code watchcui40 – https://www.manning.com/books/python-how-to

That’s all, enjoy your day!