less than 1 minute read

Introduction

File input and output (I/O) is a fundamental part of Python programming. I explored how to write data into .txt files and read it back using Python’s built-in open() function. These small building blocks help automate data handling tasks later in larger projects.


Writing to a File

f = open("data.txt", "w")
for i in range(1, 6):
    print(f"i = {i}", file=f)
f.close()

Using file=f inside print() sends output into a file instead of the screen.


Reading from a File

f = open("data.txt", "r")
data = f.read()
print(data)
f.close()

Or read line-by-line:

with open("data.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

What I learned

  • open() can write ("w") or read ("r") depending on the mode.
  • print(..., file=f) is a convenient way to write to text files.
  • Always remember to close() the file or use with open(...) to handle it safely.

What I want to do next

  • Practice with more types of text data (scores, logs, etc.)
  • Understand how file I/O connects to real-world logging and data storage.

Tags:

Updated: