DEV Community

David Makinde
David Makinde

Posted on • Originally published at daevidthegreat.hashnode.dev

Exploring .txt with Python

Welcome to the first article in the Series "Python and Files" where I will be using Python to open, read and write different file formats.

In this episode, We will be reading and writing text files in Python.

Python provides in-built standard libraries that are capable of writing and reading text files

Reading a TXT file in Python
There are different ways we might want to read our text files, these are some of them.

Read the entire text file all at once

with open('file.txt', 'r') as file:
contents = file.read()
print(contents)

First, we use the open() method to open the file in our program and we use the "r" to signify that we are going to be reading the file.

Then we save the content of the file to a variable with the method "read()"

Read line by line

with open('file.txt', 'r') as file:
contents = file.readlines()
for i in contents:
print(i)

Writing a TXT file in Python
Similarly to reading a text file, Writing a text has multiple methods, and below are some of those methods

Write the entire text file at once

with open('file.txt', 'w') as file:
file.write('Hello, world!')

In this case, we use the "w" to signify that we are going to be writing to the file.

Then we write to the file by using the "write() method"

Write line by line

lines = ['Hello', 'world', 'how', 'are', 'you']
with open('file.txt', 'w') as file:
file.writelines('\n'.join(lines))
You can use 'a' in place of 'w' when writing to an existing file ('a' stands for append)

That's all for "Exploring .txt file with Python"

Follow to get notified when new articles drop

You can reach me on Twitter 🐦

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay