How To Read File Line By Line In Python

How To Read File Line By Line In Python

to read file line by line in python we use python readlines() method.

Read File Line By Line In Python

Example1:

with open("devops.txt","r") as x:
  y=x.readlines()
  for i in y:
      print(i.strip())

Here we are reading the file line by line and we are storing the lines a list in variable y. And using for loop we are printing the lines.

Here we are using strip() method to remove new line character from each line end.

strip()

This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string.

Example2:

str = "Hi this is decoding devops\n"
print (str.strip())

here strip will remove the \n new line

Example3:

with open("devops.txt","r") as x:
    y=x.readlines()
    print(y)

output:

['hi\n', 'this\n', 'is\n', 'decoding\n', 'devops']

here in the output we are getting \n for each item in the list. so that's why we used strip() method to remove \n.

  • How To Read File Line By Line In Python
  • read file line by line in python
  • python read file line by line.
  • read file line by line python
  • how to read file line by line in python

Leave a Reply

Your email address will not be published. Required fields are marked *