Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if else condition issue
#3
no need to read the whole file in memory, just iterate over lines
in_file = 'file1.txt'
out_file = 'output.txt'
with open(in_file, "r") as f1, open(out_file, "w+") as f2:
    for line in f1:
        if line.startswith('comb'):
            pass # skip lines that start with 'comb'
        else:
            if line.startswith('result'):
                line = line[6:].lstrip() # remove result and strip whitespace from left-hand side
            f2.write(line)
now, with file2 there will be double blank lines (i.e. that is the blank lines before and after comb part). you will need to fix this if it is a problem. Also note that your blank lines in the example have single space (not actually empty lines).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
if else condition issue - by mmaz67 - Jul-17-2018, 08:51 AM
RE: if else condition issue - by gontajones - Jul-17-2018, 10:05 AM
RE: if else condition issue - by buran - Jul-17-2018, 10:52 AM
RE: if else condition issue - by mmaz67 - Jul-18-2018, 05:38 AM
RE: if else condition issue - by gontajones - Jul-18-2018, 09:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue with program not passing to other elif condition Abdirahman 6 2,213 Nov-21-2021, 07:04 AM
Last Post: Abdirahman
  else condition not called when if condition is false Sandz1286 10 6,041 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 8,314 Jun-01-2020, 06:00 PM
Last Post: penahuse

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020