Python read file into string

Previous
Next

In this post, we will see how to read a file into a string variable.

There are multiple ways to read file into String in Python.

Using read() method

Here are the steps to read file into string in python.

  • Open the file in read mode using open() method and store it in variable named file
  • Call read() function on file variable and store it into string variable countriesStr.
  • print countriesStr variable

Let’s first see content of countries.txt file which we are going to read.

$ cat countries.txt
#Country,Capital
India,Delhi
China,Shangai
Bhutan,Thimpu
France,Paris



Python code to read file into string

Output:

#Country,Capital
India,Delhi
China,Shangai
Bhutan,Thimpu
France,Paris

Using pathlib

You can also use pathlib module to copy text file content into a string variable and close the file in one line. Please note that pathlib library is available after Python 3.5 or later.

Output:

#Country,Capital
India,Delhi
China,Shangai
Bhutan,Thimpu
France,Paris

That’s all about how to read file into string in Python.

Previous
Next

Add Comment