0

I am currently trying to make a simple python script that will extract certain data from a file, and write it to a second file. In my code, I used for loop two times, while reading the file. And I have read that in order to use for loop for the second time, I need to use seek method. This is my code, and the seek method isn't giving me the result that I want. The for loop after seek method doesn't get executed.

with open("inmould_2_min_3_ekvivalent.inp", "r") as file1:
with open("phase_field_1.inp", "w") as file2:
    char = "****************************************"
    new_line = "\n"
    file2.write("*Heading\n"
                "** Job name: InputFileTemplate\n"
                "*Preprint, echo=NO, model=NO, history=NO, contact=NO\n"
                "**\n"
                "**PARTS\n"
                "*Part, name=Beam\n"
                "*Node\n"
                )
    for line1 in file1:
        if "*Node" in line1:
            for line2 in file1:
                if "*Element, type=CPS4R" not in line2:
                    file2.write(line2)
                else:
                    break
    file1.seek(0)
    for line3 in file1:
        if "*Element, type=CPS4R" in file1:
            for line4 in file1:
                if "*Nset, nset=bottom" not in line4:
                    file2.write(line4)
                else:
                    break

Can anyone please help me? I am trying to program this code for days and constantly run in to some problems.

Cro Simpson2.0
  • 103
  • 1
  • 5
  • Every time you iterate over a file object with `for`, you need to `seek` back to the start. So you need some more in there for this to ever work - though this whole approach smells wrong. Can you show some example data, and explain what you are trying to achieve in more general terms? – match Feb 10 '19 at 18:22
  • It would take me quite a while to explain what I'm doing. I was just hoping there was some quick fix for this. But since you said that whole approach smells wrong, I will try to find some other way which does not involve more than two for loops. – Cro Simpson2.0 Feb 10 '19 at 18:35
  • I think the issue is that you are opening a file, stepping through it line by line, but then trying to effectively read it from the start line by line *inside* that loop. Better to read each line once and do multiple things with it than read it multiple times. – match Feb 10 '19 at 18:45

0 Answers0