<aside> 💡
Read it. Work with it. Save it.
</aside>
Python can read and write plain text files.
Use with to open a file safely. It closes automatically when done.
with open("students.txt", "r") as file:
content = file.read()
print(content)
with open("students.txt", "r") as file:
for line in file:
print(line.strip())
.strip() removes the \n at the end of each line.
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.
with open("students.txt", "a") as file:
file.write("Bile\n")
"a" adds to the end without erasing what's already there.
| 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: |