How to Read a Text File in Python – Live Demo

Hi friends! In this article, we will talk about, how you can read a text file in Python. Also, we will see a relevant live demo.

 

Reading Files in Python with the open() Function

Python has the built-in function “open()“. As the name implies, using the open() function, you can open files in order to process them.

The open() function takes up to 2 arguments in the form of: open(filename,mode)

The second argument is optional, since if you do not specify a mode, the file is open just for reading.

So, in the first argument, you need to specify the full path for the file to be read from your Python program.

In the second argument (mode), you can use any of the below values:

  • r: opens the file for reading
  • w: opens the file for writing (overwrites the existing file)
  • a: opens the file for appending contents
  • r+: opens the file for both reading and writing
  • b: opens the file in binary mode

 

Example of Reading a Text File in Python

Now let’s see a relevant code example, via which we will be reading a simple text file from within a Python program.

This example’s code, is structured as per the below code blocks:

  • Define a list
  • Read file and save contents in the list
  • Display the list contents on screen

In addition to the above logic, we will be using exception handling.

 

The Sample Text File

In the below screenshot, you can check the sample text file that we will be using.

As you can see, the file contains 10 lines of text.

How to Read a Text File in Python - Live Demo - {essentialDevTips.com}

 

Defining the List

Since we decided to use a list for storing the file’s content, we define our list as per the below code:

#define list for storing file's content - 10 lines = 10 elements in the list
vehiclesList = ["None", "None", "None","None", "None", "None","None", "None", "None","None"]

 

Reading the File and Saving the Contents in the List

Now let’s examine the most important of our code. As you can see, in our example below, within a try…except code block that is used for exception handling, we include the call to the open() function, along with storing each line retrieved from the text file, to the list we have created for this purpose.

#enable exception handling
try:
 print("Reading contents from file and saving it to list...")
 with open('c:\demos\SampleTextFile.txt') as f:
        vehiclesList = [line.rstrip('\n') for line in f]
 print("File was successfully read")

except IOError:
 print("Error reading file...")

 

Displaying on Screen the Contents of the List

The last step, is to display the list’s contents on screen:

#display vehicleList contents on screen
print("\n")
print("Displaying list contents on screen")
for i in vehiclesList:
print(i)

 

Full Code Example – Read Text File in Python

Below, you can find the full code for the example we have created for this article.

Note that the sample text file is placed in c:\demos\SampleTextFile.txt

#define list for storing file's content - 10 lines = 10 elements in the list
vehiclesList = ["None", "None", "None","None", "None", "None","None", "None", "None","None"]

#enable exception handling
try:
 print("Reading contents from file and saving it to list...")
 with open('c:\demos\SampleTextFile.txt') as f:
        vehiclesList = [line.rstrip('\n') for line in f]
 print("File was successfully read")

except IOError:
 print("Error reading file...")

#display vehicleList contents on screen
print("\n")
print("Displaying list contents on screen")
for i in vehiclesList:
  print(i)

 

Output of our Python Program’s Execution

Below, you can find the output of our Python program’s execution, within Visual Studio Code, which is our development environment for this example.

How to Read a Text File in Python - Live Demo - {essentialDevTips.com}

 

Watch the Live Demo – Step by Step Example

 

Learn more about Programming – Enroll to our Course!

Enroll to our course on Udemy, titled  “Introduction to Computer Programming for Beginners” and get the help you need for getting started with C++, C, Python, SQL, Java, C# and the main phases of the Software Development Lifecycle.

By the time you complete this course:

  • You will know what is the required skill set in order to become a great Computer Programmer.
  • You will know more about the Programmer’s mindset.
  • You will know the main programming principles and fundamentals.
  • You will know the main phases of the Software Development Life Cycle (SDLC).
  • You will be able to start working with the following programming languages and write simple programs: C#, SQL, Java, C, C++ and Python.
Introduction to Computer Programming for Beginners - Enroll to the Course
(Lifetime access, downloadable resources, course completion certificate and more!)

Enroll to the Course

 

Learn how to work with Python and SQL Server – Enroll to our course!

Enroll to our online course “Working with Python on Windows and SQL Server Databases” with an exclusive discount, and get started with Python data access programming for SQL Server databases, fast and easy!

By the time you complete the course:

  • You will know how to install Python on Windows and set your development environment with Visual Studio Code and the proper extensions
  • You will know how to connect your Python programs to SQL Server instances and databases
  • You will know how to run different types of T-SQL queries against your SQL Server databases, from within your Python Programs
    • Execute and process SELECT, INSERT, UPDATE and DELETE T-SQL statements
    • Call Dynamic Management Views (DMVs)
    • Call aggregation functions
    • Call SQL Server global system variables
  • You will know how to execute SQL Server functions and stored procedures, from within your Python Programs
  • You will know how to use parameters and exception handling for all the above database operations within your Python code
Working with Python on Windows and SQL Server Databases - Online Course
(Lifetime access, downloadable resources, course completion certificate and more!)

Enroll to the Course

 

Recommended Online Courses:

 

Read Also:

 

Reference: {essentialDevTips.com} (https://www.essentialdevtips.com/)

© essentialDevTips.com

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)

Loading...