🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#files#io

File Input & Output

Reading a file:

with open("file.txt", "r") as f:
    content = f.read()       # entire file as string

with open("file.txt", "r") as f:
    lines = f.readlines()    # list of lines

with open("file.txt", "r") as f:
    for line in f:           # line by line (memory efficient)
        print(line.strip())

Writing a file:

with open("output.txt", "w") as f:   # overwrites
    f.write("Hello\n")
    f.write("World\n")

with open("output.txt", "a") as f:   # appends
    f.write("New line\n")

File modes:

"r" — read, "w" — write (overwrite), "a" — append, "rb" — read binary, "wb" — write binary


Always use with: It automatically closes the file even if an error occurs. Never use f = open() without a with block in production code.


YouTube • Top 10
Python Programming: File I/O
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: File I/O
Tap to View ›

Reference:

Wikipedia: I/O

image for linkhttps://en.wikipedia.org/wiki/Input/output

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT