1

Is it possible to have the following logic of a for loop in python?:

with  open("file_r", "r") as infile, open("file_1", 'w') as outfile_1, open("file_2", 'w') as outfile_2: 
    for result in re.findall('somestring(.*?)\}', infile.read(), re.S):
       for line in result.split('\n'):
           outfile_1.write(line) 

    for result in re.findall('sime_other_string(.*?)\}', infile.read(), re.S):
       for line in result.split('\n'):
           outfile_2.write(line)

I'm asking because the result of the first foor loop are written to the "outfile_1" file, but the results of the secund loop are empty in the "outfile_2" file.

2 Answers 2

3

Save infile.read() into a variable else the file will be finished in the first loop itself. Say:

with  open("file_r", "r") as infile, open("file_1", 'w') as outfile_1, open("file_2", 'w') as outfile_2: 
    contents = infile.read()

    for result in re.findall('somestring(.*?)\}', contents, re.S):
       for line in result.split('\n'):
           outfile_1.write(line) 

    for result in re.findall('sime_other_string(.*?)\}', contents, re.S):
       for line in result.split('\n'):
           outfile_2.write(line)
Sign up to request clarification or add additional context in comments.

2 Comments

And you could use comprehension to simplify the two loops.
Ouh! Thx a lot!! It works now with saving infile.read() to a variable!
0

Only if you 'rewind' infile to the start again in between reads:

... infile.read()

infile.seek(0)

... infile.read()

A file is a lot like an audiotape; when you read a reading 'head' moves along the tape and returns the data. file.seek() moves the reading 'head' to a different position, infile.seek(0) moves it to the start again.

You'd be better off reading the file just once though:

content_of_infile = infile.read()

for result in re.findall('somestring(.*?)\}', content_of_infile, re.S):
    # ...

for result in re.findall('sime_other_string(.*?)\}', contents_of_infile, re.S):
    # ...

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.