[Tutor] loop print issue

ose micah osaosemwe at yahoo.com
Tue Oct 15 08:59:34 EDT 2019


 Hello Alan, 
Thanks for the Idea. actually the input had 70 lines which contents I wanted to be used in a program and divided two outputs. I used your idea although had to make a few tweaks to it, and it works as I wanted. 
Thanks,
Ose Osamudiamen
    On Friday, October 11, 2019, 08:08:39 PM EDT, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:  
 
 On 11/10/2019 19:29, ose micah wrote:

> Thanks for your initial answer, I do appreciate it only this does not
> give the needed results:

I don't think your code did what you wanted either. I simply showed a
cleaner way of doing what you were doing. But I don't think what you
were doing was what you wanted to do. Unfortunately you didn't say what
you wanted to do so I couldn't be sure.

> The output2.txt file has only one line (the last line) with your code.

I'm guessing your input file has 37 lines?

36 went to output1 and 1 to output2? Thats what the program
(both yours and mine) says to do...

> and output1.txt has the results all on a single line against line by
> line as my initial code.

In that case add a \n to the end of the write string...

> with open('output1.txt','w') as output1
> ?? for count in range(36):
> ?? ?? ?? output1.write(xlist_file.readline() + '\n')
> 
> with open('output2.txt','w') as output2:
> ?? for line in xlist_file:
> ?? ?? ?? output2 write(line+'\n')


> However, I have a sneaky suspicion this is not actually what
> you want to do. But either way it will almost certainly be
> easier if you stop abusing sys.stdout and just open two
> output files and write() to them!

If you don't just want the first 36 lines in output1 then you need to
tell us what you do want. How do you want to split the file?
I suspect you actually want to put the lines containing
line values <36 in one file and values >36 in the other.
Is that right?

If so it should look something like(untested):

with open('output1.txt,'w') as output1:
  with open('output2.txt','w') as output2:
      for line in xlist_file:
          if int(line) > 35:
              output1.write(line + '\n')
          else output2.write(line + '\n')



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

  


More information about the Tutor mailing list