how to iterate over readlines() in python

  • Last Update :
  • Techknowledgy :

You can try the readlines() method, which calls readline() repeatedly and returns a list of the lines so read.,A string evaluates to True so long as it is not empty. The readline() method only returns an empty string at the end of the file. Even a blank line in the file contains an end of line character and readline() would return ‘\n’,I was just reading about some of these methods in the Try Python tutorials. That is a great place to go after having completed the track here. It fills in the gaps quite nicely. Someone else posted a While true: solution, but without an explanation.,You can do the same without a loop, using string’s join() method.

I tried the following in exercise one of the file I/O section:

print(line
   for line in my_file.readline())

You can try the readlines() method, which calls readline() repeatedly and returns a list of the lines so read.

for line in my_file.readlines():
   print line

In fact, the file object itself is iterable.

for line in my_file:
   print line

You can do the same without a loop, using string’s join() method.

 print '\n'.join(my_file.readlines())

I used a while/else loop like so:

my_file = open('text.txt', 'r')
i = 0
while i <= 2:
   print my_file.readline()
i += 1
else: my_file.close()

Suggestion : 2

You can write in this way. It will save you some time and give you more efficiency.

import time
def main():
   with open("childrens-catechism.txt", "r") as file:
   for line in file:
   print line,
   time.sleep(60)

Try this as per your requirements, this will do what you need.

import time
def main():
   with open("childrens-catechism.txt", "r") as file:
   for lines in file.readlines():
   if len(lines) > 0:
   for line in lines:
   print line
lines.remove(line)
else:
   print "No more lines to remove"
time.sleep(60)

lines is a list here from your txt. files, and list.remove(lines) is not a correct syntax, you trying to delete a list on list. list is a function in Python. You can delete the elements in lines like;

del lines[0]
del lines[1]
   ...

or

lines.remove("something")

On opening a file, we can convert the file lines onto a list,

lines = list(open("childrens-catechism.txt", "r"))

From this list we can now remove entries with length greater than zero, like this,

for line in lines:
   if len(line) > 0:
   # do sth
   lines.remove(line)

If you are trying to read all the lines from the file and then print them in order, and then delete them after printing them I would recommend this approach:

    import time

    try:
    file = open("childrens-catechism.txt")
    lines = file.readlines()

    while len(lines) != 0:
       print lines[0],
       lines.remove(lines[0])
    time.sleep(60)
    except IOError:
       print 'No such file in directory'

If you wanted to delete the line from the file as well as from the list of lines you will have to do this:

    import time

    try:
    file = open("childrens-catechism.txt", 'r+') #open the file
    for reading and writing
    lines = file.readlines()

    while len(lines) != 0:
       print lines[0],
       lines.remove(lines[0])
    time.sleep(60)

    file.truncate(0) #this truncates the file to 0 bytes
    except IOError:
       print 'No such file in directory'

Suggestion : 3

To process all of our olypmics data, we will use a for loop to iterate over the lines of the file. Using the split method, we can break each line into a list containing all the fields of interest about the athlete. We can then take the values corresponding to name, team and event to construct a simple sentence.,As the for loop iterates through each line of the file the loop variable will contain the current line of the file as a string of characters. The general pattern for processing each line of a text file is as follows:,We will now use this file as input in a program that will do some data processing. In the program, we will examine each line of the file and print it with some additional text. Because readlines() returns a list of lines of text, we can use the for loop to iterate through each line of the file.,Write code to find out how many lines are in the file emotion_words.txt as shown above. Save this value to the variable num_lines. Do not use the len method.

for line in myFile.readlines():
   statement1
statement2
   ...
1._
for line in myFile.readlines():
   statement1
statement2
   ...
2._
Name, Sex, Age, Team, Event, Medal
A Dijiang, M, 24, China, Basketball, NA
A Lamusi, M, 23, China, Judo, NA
Gunnar Nielsen Aaby, M, 24, Denmark, Football, NA
Edgar Lindenau Aabye, M, 34, Denmark / Sweden, Tug - Of - War, Gold
Christine Jacoba Aaftink, F, 21, Netherlands, Speed Skating, NA
Christine Jacoba Aaftink, F, 25, Netherlands, Speed Skating, NA
Christine Jacoba Aaftink, F, 25, Netherlands, Speed Skating, NA
Christine Jacoba Aaftink, F, 27, Netherlands, Speed Skating, NA
Per Knut Aaland, M, 31, United States, Cross Country Skiing, NA
Per Knut Aaland, M, 33, United States, Cross Country Skiing, NA
John Aalberg, M, 31, United States, Cross Country Skiing, NA
John Aalberg, M, 33, United States, Cross Country Skiing, NA
   "Cornelia "
"Cor"
" Aalten (-Strannood)", F, 18, Netherlands, Athletics, NA
   "Cornelia "
"Cor"
" Aalten (-Strannood)", F, 18, Netherlands, Athletics, NA
Antti Sami Aalto, M, 26, Finland, Ice Hockey, NA
   "Einar Ferdinand "
"Einari"
" Aalto", M, 26, Finland, Swimming, NA
Jorma Ilmari Aalto, M, 22, Finland, Cross Country Skiing, NA
Jyri Tapani Aalto, M, 31, Finland, Badminton, NA
Minna Maarit Aalto, F, 30, Finland, Sailing, NA
Minna Maarit Aalto, F, 34, Finland, Sailing, NA
Pirjo Hannele Aalto(Mattila - ), F, 32, Finland, Biathlon, NA
Timo Antero Aaltonen, M, 31, Finland, Athletics, NA
Win Valdemar Aaltonen, M, 54, Finland, Art Competitions, NA

Check your Understanding

Sad upset blue down melancholy somber bitter troubled
Angry mad enraged irate irritable wrathful outraged infuriated
Happy cheerful content elated joyous delighted lively glad
Confused disoriented puzzled perplexed dazed befuddled
Excited eager thrilled delighted
Scared afraid fearful panicked terrified petrified startled
Nervous anxious jittery jumpy tense uneasy apprehensive

Suggestion : 4

Using the for loop iterator and readline() together is considered bad practice.,Get monthly updates about new articles, cheatsheets, and tricks.,More commonly, the readlines() method is used to store an iterable collection of the file's lines:,readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above:

The simplest way to iterate over a file line-by-line:

with open('myfile.txt', 'r') as fp:
   for line in fp:
   print(line)

readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above:

with open('myfile.txt', 'r') as fp:
   while True:
   cur_line = fp.readline()
# If the result is an empty string
if cur_line == '':
   # We have reached the end of the file
break
print(cur_line)

More commonly, the readlines() method is used to store an iterable collection of the file's lines:

with open("myfile.txt", "r") as fp:
   lines = fp.readlines()
for i in range(len(lines)):
   print("Line " + str(i) + ": " + line)

Suggestion : 5

Example 1: Read Text File Line by Line – readline(),Example 2: Read Lines as List – readlines(),Example 3: Read File Line by Line using File Object,In this example, we will use readline() function on the file stream to get next line in a loop.

Python Program

#get file object
file1 = open("sample.txt", "r")

while (True):
   #read next line
line = file1.readline()
#check
if line is not null
if not line:
   break
#you can access the line
print(line.strip())

#close file
file1.close

Output

Hi User!
   Welcome to Python Examples.
Continue Exploring.

Suggestion : 6

Last Updated : 07 Jul, 2022

Output: 
 

Line1: Geeks
Line2: for
Line3: Geeks

Output: 

Line1 Geeks
Line2
for
Line3 Geeks

Output:

Using
for loop
Line1: Geeks
Line2: for
Line3: Geeks

Suggestion : 7

May 16, 2022 Leave a Comment

1._
with open("example.txt", "r") as f:
   for line in f:
   #do something here

Below is a simple example showing you how to read a file line by line by iterating through each line in a file using Python.

with open("example.txt", "r") as f:
   for line in f:
   #do something here

Below is an example showing how you can read a file word by word using Python.

with open("example.txt", "r") as f:
   for line in f:
   for word in line.split(" "):
   #do something here