By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,354 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

Reading a file in an inner loop [solved]

P: 46
my computer doesn't like this and hangs after creating a zero byte temp file. thanks for the help in advance

Expand|Select|Wrap|Line Numbers
  1. def Del_Instr(from_file, instr):
  2.     "del an instrument from a file dangerous indeed"
  3.     infile = open(from_file, 'r')
  4.     outfile = open('temp.tmp', 'w')
  5.     instr_num = str(instr)
  6.     for line in infile:
  7.         if 'instr' in line:
  8.            if instr_num in line:
  9.               while not 'endin' in line:
  10.                   pass                
  11.            outfile.write(line)         
  12.     close(infile)
  13.     remove(from_file)
  14.     rename('temp.tmp', from_file) 
  15.  
Oct 12 '06 #1
Share this Question
Share on Google+
3 Replies


bartonc
Expert 5K+
P: 6,596
creating an inner loop IS what you want to do, but
Expand|Select|Wrap|Line Numbers
  1.               while not 'endin' in line:
  2.                   pass                
  3.  
hangs because you never read any new lines.

I still recommend this inside the if block (you have found what you want copied)
Expand|Select|Wrap|Line Numbers
  1. outfile.write(line)
  2. try:
  3.     while True:
  4.         line = infile.next()
  5.         outfile.write(line)
  6.         if 'endin' in line:
  7.             break
  8. except StopIteration:
  9.     print 'never found endin'
  10.  
This way you get the first line written to the outfile plus the line that contains 'endin'.
Oct 12 '06 #2

bartonc
Expert 5K+
P: 6,596
It's probably better to collect all the lines that you want into a list:

out_lines = []
...
out_lines.append(line)
...

if out_lines:
# open, write and close the outfile with whatever name you want.
Oct 12 '06 #3

P: 46
I probily should of realized the infinite loop.. I will give this a try thanks alot for the help

creating an inner loop IS what you want to do, but
Expand|Select|Wrap|Line Numbers
  1.               while not 'endin' in line:
  2.                   pass                
  3.  
hangs because you never read any new lines.

I still recommend this inside the if block (you have found what you want copied)
Expand|Select|Wrap|Line Numbers
  1. outfile.write(line)
  2. try:
  3.     while True:
  4.         line = infile.next()
  5.         outfile.write(line)
  6.         if 'endin' in line:
  7.             break
  8. except StopIteration:
  9.     print 'never found endin'
  10.  
This way you get the first line written to the outfile plus the line that contains 'endin'.
Oct 12 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.