2

I'm trying to use a for line in data: loop to assign the first 3 lines of a file to 3 different variables (one line to each variable) and have it iterate for every 3 lines, so that if there were 9 lines in the file, each variable would contain 3 different lines throughout the iterations, but I cannot figure it out whatsoever.

So far my basic code looks something like this:

for line in infile:

  to_line = infile.readline()
  from_line = infile.readline()
  header_line = infile.readline()

But it's simply not working. It's assigning every other line of my file to each variable (i.e. 4 lines to each variable and not all lines are being assigned).

The premise of the program is to process an input file containing 9 lines (a "to" line, "from" line, and "subject" line for each email [3 emails total]) and then sort them based on whether or not they are spam or "good" mail.

A sticky stipulation that I have for this is that it's for a college course and I'm not allowed to use anything that we have yet to go over in class (we're 8 weeks in so we have a small knowledge base of basic information to use). If anyone responds with anything that I cannot use, I will let you know.

5 Answers 5

10

You don't actually need to call readline, just iterating over the file is enough. You can use the zip function to regroup the lines. Therefore, the generic solution would look like

for odd_line,even_line in zip(infile, infile):
     # Do something

If you want to create a list of all even and odd lines first (and that's seldomly a good data structure), you can just append to a list, like this:

odd_lines = []
even_lines = []
for odd_line,even_line in zip(infile, infile):
     odd_lines.append(odd_line)
     even_lines.append(even_line)

Alternatively, use

lines = list(infile)

to get a list of all lines, and then slices to extract a part of the file. For example,

even_lines = lines[1::2]

Another alternative is using an iterator with a while loop. Simply call next multiple times. For example, this prints all odd lines:

iterator = iter(infile)
while True:
  try:
    odd_line = next(iterator)
    print(odd_line)
    even_line = next(iterator)
  except StopIteration:
    break

If you don't want to use break (and that's crazy), you can simply catch the exception outside of the loop:

iterator = iter(infile)
try:
  while True:
    odd_line = next(iterator)
    print(odd_line)
    even_line = next(iterator)
except StopIteration:
  pass # end of file reached

Instead of using an iterator, you can also use readline:

odd_lines = []
even_lines = []
while True:
  line = infile.readline()
  if not line: # End of file reached
    break
  odd_lines.append(line)

  line = infile.readline()
  if not line: # End of file reached
    break
  even_lines.append(line)

Again, if you really can't use break statements, you can fake them:

odd_lines = []
even_lines = []
go_on = True
while go_on:
  line = infile.readline()
  if even_line:
    odd_lines.append(line)
    line = infile.readline()
    if line:
      even_lines.append(line)
    else:
      go_on = False
8
  • Sadly my professor is apparently VERY strongly opposed to using "break", as we automatically lose 50% off of our project grade if our program contains the "break" or "continue" statement, thanks for responding all the same though!
    – Pyrok
    Mar 25, 2012 at 1:53
  • +1, Note that with the first approach you can "simply" iterate like this: for (to_line, from_line, header_line) in zip(lines[0::3],lines[1::3],lines[2::3]):
    – KillianDS
    Mar 25, 2012 at 1:54
  • 1
    @user1290693 That sounds like a task for the psychiatric faculty. Seriously, there's absolute nothing wrong with break and continue. Are you certain that your professor demands such insane restrictions? I amended this answer with a version that uses neither zip nor break.
    – phihag
    Mar 25, 2012 at 1:59
  • 1
    Oh my. The test case as a .doc file says it all. I'm sorry for you. If you ever happen to study abroad in Germany, I recommend an excellent Python course at my local university, taught by Python experts.
    – phihag
    Mar 25, 2012 at 2:13
  • 1
    Not as bad as one of my friends in a first year IT course, who has to write a non-trivial program without using lists, dicts, try... catch or def. The lecturer claims this is to 'give them a solid foundation in the basics.' Mar 25, 2012 at 3:32
5

Since files are iterators, they can be zipped into groups. This means that the answer to your question is a very simple piece of code:

with open(filename) as f:
    for to_line, from_line, header_line in zip(f, f, f):
        print (to_line, from_line, header_line)

For students who are not allowed to use zip, the following would also work:

f = open(filename)
try:
    while True:
        to_line, from_line, header_line = next(f), next(f), next(f)
        print (to_line, from_line, header_line)
except StopIteration:
    pass
finally:
    f.close()
3
  • This is where the stipulation comes in pertaining to things that we have yet to go over in class not being allowed on the program. We have yet to talk about "zipping" and as such I'm afraid that I wouldn't be allowed to use this, is there perhaps some way to modify this to not include the use of "zip"? Thanks for your response nonetheless.
    – Pyrok
    Mar 25, 2012 at 2:22
  • @Pyrok I updated the answer to include a zipless variant. Still, it's too bad you can't use zip(), it is a basic looping idiom and a fundamental part of the language. Mar 25, 2012 at 3:49
  • +1 That's what the OP really wanted. I added parentheses on print since the question is tagged with python-3.x (and a print function is so much better than a print statement anyways). I barely dare to edit the legendary @raymondh, so feel free to revert it.
    – phihag
    Mar 25, 2012 at 3:50
3

This isn't working because the beginning of the loop (i.e., for line in infile:) reads the next line from infile, which you basically throw away by not using it. An alternative to this would be reading all lines upfront into a list, and then working through the list:

# read all lines from the file into a list, where each list element is one line
lines = infile.readlines()

# iterate through the list three lines at a time, until you run out of lines
line_number = 0
while line_number < len(lines):
    to_line = lines[line_number]
    from_line = lines[line_number+1]
    header_line = lines[line_number+2]
    line_number += 3
6
  • I tried using this however I first received an error saying that "list object has no attribute 'length'" in the "while line_number < lines.length()" line, so I changed it from "lines.length() to len(lines):" but now when I run it and try to "print(to_line)" it just outputs a few blank lines to the shell, any ideas?
    – Pyrok
    Mar 25, 2012 at 2:01
  • I'm sorry, I've got my language syntax messed up. I've corrected it for you above. Mar 25, 2012 at 2:18
  • It's ok, I went ahead and changed the syntax once I noticed the discrepancy, however when I attempt to run this, it simply returns 3 blank lines to the shell and does nothing else (the blank lines are because I was attempting to print(to_line) to see how the lines were being stored, any ideas?
    – Pyrok
    Mar 25, 2012 at 2:28
  • Wow, tonight is not my night. Fixed again. Mar 25, 2012 at 2:30
  • This will not work if the number of lines in the file is not a multiple of 3.
    – the wolf
    Mar 25, 2012 at 3:24
1

Each iteration of the for loop reads a line from infile into line. Try this code:

for line in infile:
    print line

This reads each line of infile into line and prints each line.

So, when you do infile.readline() inside the loop, you are actually reading another line, since the first one was read into line.

It's easy to get confused when you read for line in infile in english, since you don't realize that this actually means: "Read a line from infile into line and execute the code below. Do it again until there are no more lines to read."

Since you are only reading 3 lines at a time, you could do something like:

infile = open("yourfilename.txt")
for i in range(3):
   to_line = infile.readline()
   from_line = infile.readline()
   header_line = infile.readline()
   # Do something with the lines you just read

This loop will be executed 3 times (see range(3)), each time reading 3 lines into the appropriate variables.

1
  • I was very close to this on my latest trial, however my problem here stems from needing the loop to run until there are no more lines in the file. For instance, each 3 lines accounts for 1 single email in the file(hence the variable names), and there are always going to be multiple emails in the file. So during one run of the loop, the 3 variables will each hold one line, and then will be processed and sorted into either spam or good mail, and then I need the loop to restart for the following 3 lines (or the next email), is there a way to make this happen?
    – Pyrok
    Mar 25, 2012 at 1:53
0

This is a great use for a dictionary of lists. With that, you can have a general solution that will return a dictionary of each line number index.

First, generate some lines:

with open('/tmp/lines.txt','w') as fw:
    for line in range(10):     # 0 - 9!!!
        print >>fw, 'This is line',line

Now, read those lines into a data structure that has every nth line indexed:

n=3        
with open('/tmp/lines.txt','r') as fr:
    i=0
    ells={i:[] for i in range(n)}
    for line in fr:
        ells[i%n].append(line.strip())
        i+=1

print ells
3
  • I'm afraid that I won't be able to use "with" as it's something that we have yet to cover in our course, (along with the .strip() method and using the "as fr:" and "as fw:" statements, is there perhaps a way to do this without including those?
    – Pyrok
    Mar 25, 2012 at 2:31
  • Sure. Just replace with open(...) as fr: with fr=open(...) and change the indenting below the with
    – the wolf
    Mar 25, 2012 at 2:47
  • for the .strip() method -- just remove it and you will have line terminators at the end of your strings.
    – the wolf
    Mar 25, 2012 at 2:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.