Skip to content
Python Guides
Python Guides
  • Home
  • Python Tutorials
    • Start Here
    • Python Tkinter
    • Python Pandas
    • Python NumPy
    • Python Turtle
    • Django
    • Matplotlib
    • Tensorflow
    • PyTorch
    • Scikit-Learn
    • Scipy
  • Machine Learning
  • Artificial Intelligence
  • YouTube

Python read a file line by line example

March 22, 2021February 22, 2021 by Bijay Kumar

In this Python tutorial, we will learn, how to read a file line by line in Python with a few examples. Apart from Python read a file line by line we will also cover the below topics:

  • Python read file line by line
  • Python read file line by line into array
  • Python read file line by line into a dictionary
  • Python read file line by line and search string
  • Python read file line by line without a newline
  • Python read file line by line into a list
  • Python read file line by line into a set
  • Python read file line by line and write to another file
  • Read file line by line for loop python
Table of Contents show
1. Python read file line by line
2. Python read file line by line into array
3. Python read file line by line into dictionary
4. Python read file line by line and search string
5. Python read file line by line without a newline
6. Python read file line by line into a list
7. Python read file line by line into a set
8. Python read file line by line and write to another file
9. Read file line by line for loop python

Python read file line by line

Now, we can see how to read file line by line in python.

  • In this example, I have taken a line as [“Welcome\n”,”to\n”,”Pythonguides\n”] , and to open the file , I have used file = open(‘line.txt’, ‘w’) and ‘w’ mode to write the lines. Here line.txt is the name of the file.
  • To read the lines, I have used Lines = file.readlines(), for loop, is used.

Example:

Line = ["Welcome\n","to\n","Pythonguides\n"]
file = open('line.txt', 'w')
file.writelines(Line)
file.close()
file = open('line.txt', 'r')
Lines = file.readlines()
for line in Lines:
	print(line)

To get output, I have used print(line). In the below screenshot, we can see the line from the file as the output.

Python read file line by line
Python read file line by line

This is how we can read file line by line in Python.

Check out Python binary tree implementation and How to read video frames in Python.

Python read file line by line into array

Now, we can see how to read file line by line into array in python.

  • In this example, I have defined a function as fruits and an argument fruitsname is passed.
  • An empty array is defined and the argument is opened as f and to read the line. The for line in f is used and to append the line into the array, array.append is used.
  • The fruits file is passed as the parameter in the function.

Example:

def fruits(fruitsname):
        array = []
        with open(fruitsname) as f:   
                for line in f:
                        array.append(line)
                print(array)
fruits('fruits.txt')

The below screenshot shows the content of the file

How to read file line by line into array in Python
How to read file line by line into array in Python

The line which is present in the file is appended into the array as the output. You can refer to the below screenshot for the output.

Python read file line by line into array
Python read file line by line into array

This code, we can use to read file line by line into array in Python.

Python read file line by line into dictionary

Now, we can see how to read file line by line into dictionary into python.

  • In this example, An empty dictionary is declared and the file dictionary.txt is opened.
  • The for line in file is used to read the file line by line and key, value is assigned line.split() is used to split the list.
  • To assigned the key and value, I have used dictionary[key] = value.
  • To print the dictionary, I have used print(dictionary).

Example:

dictionary = {}
file = open("dictionary.txt")
for line in file:
    key, value = line.split()
    dictionary[key] = value
print(dictionary)

The below screenshot show the content of the file.

Python read file line by line into dictionary
Python read file line by line into dictionary

Here, we can see the output as the dictionary is printed by reading the file. You can refer to the below screenshot for the output.

Python read file line by line into dictionary
Python read file line by line into dictionary

This is how to read file line by line into dictionary in Python.

You may like to read, Python program to find sum of n numbers and How to add two numbers in Python.

Python read file line by line and search string

Here, we can see how to read file line by line and search string in python.

  • In this example, I have defined a function as a file and passed the arguments filename and search.
  • To search the string, I have opened the file string.txt and to read the file, I have used for line in read to search the string.
  • If the string is in line return True and return False if the word ‘Hello’ is present in the file it prints string present in the file else the string not present in the file.

Example:

def file(file_name, search):
     with open("string.txt", 'r') as read:
        for line in read:
            if search in line:
                return True

     return False
if file('string.txt', 'Hello'):
    print('string present in the file')
else:
    print('String not present in the file')

The below screenshot show the content of the file.

Python read file line by line and search string
Python read file line by line and search string

As the string “Hello” is present in the file, we can see the output as String present in the file. You can refer to the below screenshot for the output.

Python read file line by line and search string 1
Python read file line by line and search string

This is how to read file line by line and search string in Python.

Python read file line by line without a newline

Now, we can see how to read file line by line without a newline in python.

  • In this example, I have opened the file string.txt and used “r” mode to read the file.
  • To read the file line by line without a newline, I have used .replace(‘\n’).
  • To get the output print(string) is used.

Example:

file=open("string.txt","r")  
string=file.read().replace('\n','')  
print(string) 

The below screenshot show the content of the file.

Python read file line by line without a newline
Python read file line by line without a newline

The below screenshot show that the file is read without newline as the output. The below screenshot shows the output.

Python read file line by line without a newline
Python read file line by line without a newline

The above code, we can use to read file line by line without a newline in Python.

Python read file line by line into a list

Let’s see how to read file line by line into a list in python.

  • In this example, I have opened a file number.txt and ‘r’ mode to read the file as f, and an empty list is defined as list = [ ] and to read line by line for line in f is used.
  • To append the line from the file into the list, I have used lines.append(line.strip()) the line.strip is used.
  • The line.strip() is used to copy the string and remove the characters. To get the output, print(lines) is used.

Example:

with open ("number.txt",'r' ) as f:
    list = []
    for line in f:
        lines.append(line.strip())
        print(lines)

The below screenshot show the content of the file number.txt.

Python read file line by line into a list
Python read file line by line into a list

In the below screenshot, we can that the content from the file number.txt is appended in the list as the output.

Python read file line by line into a list 3
Python read file line by line into a list

The above code, we can use to read file line by line into a list in Python.

Python read file line by line into a set

Now, we can see how to read file line by line into a set in python.

  • In this example, a set is used to read the file into a set the content from the file chocolate.txt is read by using .read() and .split() is used to split the string.
  • To get the output, I have used print(chocolate).

Example:

chocolate =  set(open('chocolate.txt').read().split())
print(chocolate)

The below screenshot show the content of the file.

Python read file line by line into a set
Python read file line by line into a set

The content from the file chocolate.txt is appended into the set as the output. You can refer to the below screenshot for the output.

Python read file line by line into a set
Python read file line by line into a set

This is how to read file line by line into a set in Python.

Python read file line by line and write to another file

Here, we can see how to read file line by line and write to another file in python.

  • In this example, I have opened the file chocolate.txt as f1.
  • To write the content into another file, I have opened another file as newfile.txt and f.write is used to write the file, and f.read is used to read the file.
  • The .strip() is used to remove the character from the left and right of the argument.

Example:

with open("chocolate.txt") as f1,\
        open("newfile.txt", "w") as f:
    f.write(f1.read().strip())

The below screenshot shows the content of the file chocolate.txt.

Python read file line by line and write to another file input

In the below screenshot, we can see that the content from the file chocolate.txt into newfile.txt.

Python read file line by line and write to another file
Python read file line by line and write to another file

This is how to read file line by line and write to another file in Python.

Read file line by line for loop python

Now, we can see how to Read file line by line for loop in python.

In this example, I have opened a file python.txt as f and for loop is used as for line in f to read the line of the file.

Example:

with open('python.txt') as f:
     for line in f:
       print(line)

The below screenshot shows the content of the file

Read file line by line for loop python
Read file line by line for loop python

All the lines from the file python.txt are read as the output. You can refer to the below screenshot for the output.

Read file line by line for loop python
Read file line by line python for loop

The above code, we can use to read file line by line for loop in Python.

You may like the following Python tutorials:

  • Create and modify PDF file in Python
  • Python get all files in directory
  • How to read a text file using Python Tkinter
  • Python read a binary file
  • Python copy file
  • Python File methods
  • Python write list to file with examples
  • Python intersection of sets

In this tutorial, we have learned about Python read a file line by line example, and also we have covered these topics:

  • Python read file line by line
  • Python read file line by line into array
  • Python read file line by line into a dictionary
  • Python read file line by line and search string
  • Python read file line by line without a newline
  • Python read file line by line into a list
  • Python read file line by line into a set
  • Python read file line by line and write to another file
  • Read file line by line for loop python

Bijay Kumar MVP
Bijay Kumar

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

enjoysharepoint.com/
Post navigation
Create and modify PDF file in Python
Python intersection of sets

Follow us in Twitter & Facebook

Follow @PythonGuides


Recent Posts

  • Python Scipy Minimize [With 8 Examples]
  • Expense Tracking Application Using Python Tkinter
  • Convert PDF file to Docx in Python 
  • Python Scipy Distance Matrix
  • Complete Guide To Artificial Intelligence
  • About PythonGuides.com
  • Contact
  • Privacy Policy
  • Sitemap
© 2022 Python Guides