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.
Table of Contents
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 namedfile
- Call
read()
function onfile
variable and store it into string variablecountriesStr
. - print
countriesStr
variable
Let’s first see content of countries.txt
file which we are going to read.
#Country,Capital
India,Delhi
China,Shangai
Bhutan,Thimpu
France,Paris
Python code to read file into string
1 2 3 4 5 |
with open('countries.txt','r') as file: countriesStr = file.read() print(countriesStr) |
Output:
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
.
1 2 3 4 5 |
from pathlib import Path countriesStr=Path('countries.txt').read_text() print(countriesStr) |
Output:
India,Delhi
China,Shangai
Bhutan,Thimpu
France,Paris
That’s all about how to read file into string in Python.