Skip to main content
Read Text File Using Python

Python Read Text File

in this python tutorial, I’ll demonstrate Reading a text file using python. Python has built-in file creation, writing, and reading capabilities. There are two sorts of files that can be handled: text files and binary files.

in the text file, Each line of text is terminated with a special character called End of Line(EOL), which is the new line character (‘\n’) in python by default.

Whereas the Binary files have content machine understandable binary data, there is no terminator for a line as a text file.

We ll following steps to read a file in python:

  • We’ll open a file using open() function.
  • The file object have read(), readline(), or readlines() method to read content from text file.
  • Finally, Close the file using close() function.

How To Read Text File

The following code help to read all texts from the test.txt file into a string.

with open('text.txt') as file:
lines = file.readlines()

In the above code,

with : We have opened the file using with the statement. The with statement help to close the file automatically without calling the close() method.

without with, you need to explicitly call the close() method to close the file.

open(): the open method help to open a file. The open() method returns a file object that you can use to read text from a text file. The syntax is:

open(path_to_file, mode)

Where is parameter is:

  • path_to_file : This is the file’s location. It might be the current directory or the path.
  • mode : There are 6 access modes in python.This help to
ModeDescription
'r'Open file for reading text
'r+'Open file for reading and writing text. Raises I/O error if the file does not exists.
'w'Open a file for writing text.
'w+'Open a file for writing and reading text. data is truncated and over-written for already exist file
'a'Open a text file for appending text
'a+'Open a text file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.

How To Read UTF-8 text files Using Python

The above code example will work with ASCII Text type files. However, if you’re dealing with other languages such as Chinese, Japanese, and Korean files, those are UTF-8 type files.

To open a UTF-8 text file, You need to pass the encoding='utf-8' to the open() function.

with open('test.txt', encoding='utf8') as file:
lines = file.readlines()

Leave a Reply

Your email address will not be published. Required fields are marked *