<aside> 💡

Read it. Work with it. Save it.

</aside>


1. Text Files

Python can read and write plain text files.

Use with to open a file safely. It closes automatically when done.

🧑‍💻 Read a File

with open("students.txt", "r") as file:
    content = file.read()

print(content)

Read Line by Line

with open("students.txt", "r") as file:
    for line in file:
        print(line.strip())

.strip() removes the \n at the end of each line.

Write a File

with open("students.txt", "w") as file:
    file.write("Ahmed\n")
    file.write("Faadumo\n")
    file.write("Hodan\n")

"w" overwrites everything in the file.

Append to a File

with open("students.txt", "a") as file:
    file.write("Bile\n")

"a" adds to the end without erasing what's already there.

📌 Summary

Task Code
Read a file open("file.txt", "r")
Read all text file.read()
Read lines for line in file:
Strip newlines line.strip()
Append to a file open("file.txt", "a")
Overwrite a file open("file.txt", "w")
Safe open with open(...) as file:

2. CSV