DEV Community

still-purrfect
still-purrfect

Posted on

Working With .txt Files in Python: Simple but Powerful

Not every file is complex.
Sometimes, all you need is a simple text file.
And that’s exactly where .txt files come in.
With file handling, we’ve learned how Python can read and write data.
Now let’s make it more practical by focusing on one of the simplest and most commonly used file types: .txt files.
A .txt file is just a plain text file. No formatting, no special structure just raw text.

🔹 Writing to a .txt File

file = open("notes.txt", "w")

file.write("This is my first text file.")

file.close()
Enter fullscreen mode Exit fullscreen mode

This creates a file called notes.txt and writes content into it.

🔹 Reading from a .txt File

file = open("notes.txt", "r")

content = file.read()
print(content)

file.close()
Enter fullscreen mode Exit fullscreen mode

This reads everything inside the file.

🔹 Adding More Content

file = open("notes.txt", "a")

file.write("\nThis is a new line.")

file.close()
Enter fullscreen mode Exit fullscreen mode

This adds new content without deleting what was already there.

🔹 Using "with" (Better Practice)

Instead of manually closing files, Python gives a cleaner way:

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

This automatically handles closing the file.

💡 Why .txt Files Matter

.txt files are simple, but very useful:

  • Storing notes
  • Saving logs
  • Writing simple data
  • Testing file handling concepts They are often the starting point before moving into more complex file types like CSV or databases.

🌱 Challenge

Create a program that:

  1. Writes your name and a short message into a .txt file
  2. Reads the file and prints the content
  3. Adds another line to the file. Keep it simple and focus on understanding the flow.

Next, we’ll move into exception handling, where your program learns how to deal with errors when working with files and user input.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.