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.
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.
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.
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
Recommended Online Courses:
- SQL Server 2022: What’s New – New and Enhanced Features
- Introduction to Azure Database for MySQL
- Working with Python on Windows and SQL Server Databases
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- A Guide on How to Start and Monetize a Successful Blog
- Data Management for Beginners – Main Principles
Read Also:
- Main Data Structures in Python
- Understanding Variables in Python
- SyntaxError: invalid syntax when using IF in Python – How to Resolve it
- IndexError: list index out of range – How to Resolve it in Python
- Input and Output in Python
- How to Write a “Hello World” App in Visual C++
- How to Write a “Hello World” App in C#
- How to Get Started with SQL Server – First Steps
- Benefits of Primary Keys in Database Tables
- How to Rebuild All Indexes Online for a SQL Server Database
- What’s the Best Allocation Unit Size when Formatting a USB Flash Drive?
Reference: {essentialDevTips.com} (https://www.essentialdevtips.com/)
© essentialDevTips.com
Rate this article:
Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 15 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.