How to Read a Text File in Python?
Hello,
Now, let's see an example of python read text file example. you can see python read txt file example. you will learn python read file from directory. step by step explain how to read text file in python. So, let's follow a few steps to create an example of how to read text file in python as string.
There are three following methods to read text file with open() functions.
read(): Read text file content as string.
readline(): Read single line from text file as string.
readlines(): Read all lines from text file as python list.
Without any further ado, let's see the below code examples below one by one.
You can use these examples with python3 (Python 3) version.
Example 1: using read()
main.py
# Python read text file using read() with open('readme.txt') as f: contents = f.read() print(contents)
Output:
Hi ItSolutionstuff.com! This is body Thank you
Example 2: using readline()
main.py
# Python read text file using readline() with open('readme.txt') as f: content = f.readline() print(content)
Output:
Hi ItSolutionstuff.com!
Example 3: using readlines()
main.py
# Python read text file using readlines() with open('readme.txt') as f: contents = f.readlines() print(contents)
Output:
['Hi ItSolutionstuff.com!', 'This is body', 'Thank you']
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Generate Text File from List Example
- Python Create Text File If Not Exists Example
- Python Create Text File in Specific Directory Example
- How to Create Multiline Text File in Python?
- Python Create an Empty Text File Example
- How to Create Text File in Python?
- How to Get All Files from Directory in Python?
- Python Post Request with Basic Authentication Example
- Python Get File Extension from Filename Example
- Python Check if Date is Weekend or Weekday Example
- Python PATCH Request with Parameters Example
- How to Subtract Months to Date in Python?