How to Read a Text File in Python?
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()
# Python read text file using read() with open('readme.txt') as f: contents = f.read() print(contents)
Hi ItSolutionstuff.com! This is body Thank you
Example 2: using readline()
# Python read text file using readline() with open('readme.txt') as f: content = f.readline() print(content)
Example 3: using readlines()
# Python read text file using readlines() with open('readme.txt') as f: contents = f.readlines() print(contents)
['Hi ItSolutionstuff.com!', 'This is body', 'Thank you']
I hope it can help you...
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?