DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Reading and Writing Files in Python Explained Simply

Working with files lets your programs store and retrieve data. Python makes basic file operations easy with the open() function.

Opening a file

Use open() with the file name and mode.

Common modes:

  • "r": read (default)
  • "w": write (overwrites if file exists)
  • "a": append (adds to end)
  • "r+": read and write
file = open("example.txt", "r")
Enter fullscreen mode Exit fullscreen mode

Always close the file when done:

file.close()
Enter fullscreen mode Exit fullscreen mode

Better: use with (automatically closes):

with open("example.txt", "r") as file:
    # work with file
# file is closed here automatically
Enter fullscreen mode Exit fullscreen mode

Reading from a file

Read entire content:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
Enter fullscreen mode Exit fullscreen mode

Read line by line:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip removes newline
Enter fullscreen mode Exit fullscreen mode

Read all lines into a list:

with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines)
Enter fullscreen mode Exit fullscreen mode

Writing to a file

Write (overwrites):

with open("output.txt", "w") as file:
    file.write("Hello, file!\n")
    file.write("Second line.")
Enter fullscreen mode Exit fullscreen mode

Append:

with open("output.txt", "a") as file:
    file.write("\nNew appended line.")
Enter fullscreen mode Exit fullscreen mode

Write multiple lines:

lines = ["First line\n", "Second line\n", "Third line\n"]

with open("list.txt", "w") as file:
    file.writelines(lines)
Enter fullscreen mode Exit fullscreen mode

Simple examples

Save user input to a file:

name = input("Enter your name: ")

with open("names.txt", "a") as file:
    file.write(name + "\n")
Enter fullscreen mode Exit fullscreen mode

Read and display a file:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found.")
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Use with to avoid forgetting to close files.
  • Specify encoding if needed: open("file.txt", "r", encoding="utf-8")
  • Handle FileNotFoundError when reading non-existent files.
  • Writing in "w" mode deletes existing content.

Quick summary

  • Open files with open() and use with for safety.
  • Read with .read(), .readlines(), or loop.
  • Write with .write() or .writelines().
  • Use "r" for reading, "w" for writing, "a" for appending.
  • Always handle possible errors.

Practice reading from and writing to simple text files. File operations are essential for persistent data in Python programs.

Top comments (0)