How to Open, Read and Write Text files in Python [With Examples]


The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

This article is about the ways to open, read and write text files in Python with examples. This will be done by using different methods of inputting text into a file like reading from stdin or writing to an already existing file

The “write text file python” is a command-line tool that allows users to open, read and write text files in Python. The example below will show how to create a new text file and then write some text into it.

How to Open, Read and Write Text files in Python [With Examples]

Python has always been the preferred option for most IT professionals who like automating tasks. To automate numerous IT operations using Python, you just need a few lines of code, one of which is dealing with files. Python can read, write, and create files, among other things.

With plenty of examples, you’ll learn how to develop Python code to open, read, and write to text files in this course.

Let’s get this party started!


This lesson will be presented in a step-by-step format. If you want to join in, make sure you have the following items:

  • Python v3.6 or later — On a Windows 10 system, this course will use Python v3.9.2.

How Do You Install Python 3.6? Related:How Do You Install Python 3.6?

Using Python to Open a Text File

Let’s get started with this lesson by learning how to open a file in Python for reading.

1. Launch your preferred coding editor, such as VS Code.

2. Create a basic text file named devops.txt in the home directory () with the text *”*Hello, ATA friends.”

3. Create a file and paste the Python code below into it, then save it as ata python read file in your home directory as a Python script.

# The file object is newfile, the file to be opened is devops.txt, and the default Access mode is read newfile = open(‘devops.txt’) # Specifying “read” as the only access mode. # open(‘devops.txt’, ‘r’) newfile print(newfile)

The Python built-in function open() is used in the preceding script to open the devops.txt file for reading without defining an access mode. Following that, the open() function produces a file stream, which is saved in the newfile variable.

Once you’ve created a file object, you may use its methods and properties to execute different tasks. You must set a certain mode when opening files, depending on what you plan to do with the file, as stated above in the inline comments. In Python, there are many ways to open files.

  • r — Allows you to read the file. This is the default manner of access.
  • w — This command opens the file for writing.
  • x – If no file exists, this option creates one, but if one does, it fails.
  • a — Appends data to the end of the file after opening it for writing.
  • b — Uses binary mode to open the file. This mode is for working with files that aren’t text, such as pdfs, photos, and so on.
  • t — Text mode opens the file. This is the standard setting.
  • + – Allows you to read or write to a file.

4. Run the Python script now.

ata python read file python ata python read file

The file stream will be shown in the output, together with information such as the file type, access mode, and encoding.

Using Python to open a text fileUsing Python to open a text file

Once the file is open, you may read, write, and alter it in a variety of ways.

Using Python to Read a Text File

It’s time to do something with a file that you’ve opened in Python. First, let’s look at how to read a text file. If you want to read the contents of a file, you’ll need to use the read Python function ().

Replace the content in the ata python read file Python script in your code editor with the following Python code, save, and run it.

The following script reads the whole file as a file stream, one line at a time, and just the first five characters of each line.

file = open(‘devops.txt’, ‘r’) # Reading the file as a single file stream # Reads the full file in one go and saves it to memory. content = read content () print(read content) # Using the with keyword # to iterate over each line in the text file and reading each line one at a time with open(‘devops.txt’, ‘r’) as line: # Reads a single line of text from a file. line text = c; line text = c; line text = c; print(line text) readline() # Reading the first five characters of each line with open(‘devops.txt’, ‘r’) as line: # Iterating over each line in the text file with the with keyword # and reading the first five characters of each line with open(‘devops.txt’, ‘r’) as line: # Reads a set of characters from a single line of text in a file. = read char (5) print(read char)

When reading rows or data, reading a range, and merely reading the first row, the outputWhen reading rows or data, reading a range, and merely reading the first row, the output

Using Python to Read a CSV File

Python can open basic text files, as you’ve discovered. In reality, CSV files are essentially text files with a specified structure. To read CSV rows, you could use the open() method with the read() or readline() methods, although this isn’t very helpful. Why? Because the read methods aren’t aware of the schema of a CSV file.

What is a CSV File and How Do I Make, Open, and Work With One?

Use the CSV Python module to read a CSV file so that Python can interpret the data it contains.

Assuming you’re still in your code editor, here’s what you should do:

1. Paste the following CSV data into a new tab and save it as ata csv demo.csv. This CSV data has four columns and four rows, as you can see.

Sitepage, PreviousUserCount, UserCountTotal 02-01-2021,61,5336, 03-01-2021,42,5378, 05-01-2021,65,5469, 04-01-2021,26,5404,

2. Create the following Python script in a new tab and save it as a Python script with a name of your choice. This Python script is as follows:

  1. The csv module is imported to make the methods accessible.
  2. The ata csv demo.csv file is opened for reading.
  3. The reader() function reads each row in the CSV file, informing Python that each row is delimited by a comma.
  4. For each CSV record, a for loop is used to read the text in each row, producing a Python list.

# Import the CSV module using the import csv command. Open the CSV file for reading and use open(‘ata csv demo.csv’, ‘r’) to iterate over each row as csv row: # # csv data = csv.reader(csv row, delimiter=’,’) csv data = csv.reader(csv row, delimiter=’,’) csv data = csv.reader(csv row, delimiter=’,’) csv_ # The for-loop is used to output specified rows from csv files and iterates across the range() function for in range(5): print(next(csv data)) print(read)

You can see how the script iterated over the CSV file to only display the first 5 rows in the result below.

When reading just 5 rows from a CSV file, this is the output.When reading just 5 rows from a CSV file, this is the output.

Using Python to Add to a Text File

You aren’t limited to reading when you open a text file in Python. Text files may also be written to. In this part, we’ll look at how to add text to an existing file.

You have two options for writing to a text file:

  • write() – Saves the contents of the file as a string.
  • writelines() — Writes many strings to a file at the same time.

Let’s look at how to add data to a text file now. To do so, create a new tab in your code editor, copy and paste the Python code below, save it as a Python script with a name of your choice, and run it.

The script below uses the write() function to add a single line to the devops.txt file you prepared previously. The writeLines() function is then used to attach numerous lines at once.

# With open(‘devops.txt’, ‘a’) as file, open the file for appending (a) and start reading each line: file. file write(“nAdding five more ATA friends”) [‘nAdding 5 more ATA friend’, ‘nAdding 15 more ATA buddy’]) writelines

add data to a text fileadd data to a text file

Using Python to write data to a CSV file

You should now be able to open a CSV file using Python. You’ll need to add data to CSV files for a variety of reasons, like adding customer information, employee wage records, and employee ID. Python simplifies the process of writing CSV files.

Open a new code editor tab and paste the following Python script into your code editor, save, and run it to add rows to the same file devops.csv that you produced before.

# the csv module is being imported # open function inside with statement with import csv Because the csv module handles newlines (universally), you used newline here. as csv file with open(‘devops.csv’,’a’, newline=”): # open() method with newline=” and append mode “a” write csv = csv.writer(csv file, delimiter=’,’,’,’,’,’,’,’,’,’,’,’,’,’,’,’,’,’,’, # write csv.writerow([’08-08-2021′,’68’,’8888′, ‘′]) # csv.writerow([’08-08-2021′,’68’,’8888′, ‘′]) # csv.writerow([’08-08-2021′,’68’,’8888′, ‘’ Using Python, run the writing into script.

Check out the final row in devops.csv!

Added a row to the CSV fileAdded a row to the CSV file


You’ve learned how to use Python to open, write, and read several file formats today. When opposed to doing these tedious operations manually, Python dramatically minimizes the likelihood of human mistake.

Why not use Python to automate more of your data handling chores now that you can handle data at rates you never thought possible?

Python is a high-level, interpreted, dynamic programming language. It can be used for many different things such as web development, system administration, and scientific computing. Python also has text file support built in, which makes it very easy to read and write text files. Reference: python read text file line by line.

Frequently Asked Questions

How do you open read and write files in Python?

A: To open files in Python, you have to first create a file object with your desired filename. You can then use the following methods to read or write values from or into that file object.

How do you read and write to a text file in Python?

A: textfile.write(contents of the file

How do I open a text file in write and read mode?

A: You can open a text file in read and write mode by double clicking on it.

Related Tags

  • python write to text file line by line
  • how to read text file in python pandas
  • how to read a text file in python
  • python with open file
  • file handling in python examples

Table of Content