0

I have a test.txt that contains:

-
anything1
go
-
anything2
go

And i wanna replace the '-' with my list and some query. Here is my code:

x = ['1', '2']
i=0
with open("test.txt", "r") as fin:
    with open("result.txt", "w") as fout:
        for line in fin:
            fout.write(line.replace('-','\nuse '+(str(x[i]))+'\ngo\n'))
            i+=i

But my result is:

use 1
go
anything1 
go

use 1
go
anything2 
go

I need that the second 'use' be 'use 2' and not 'use 1'.

How I can fix this?

Thanks

2
  • 1
    Consider what i+=i does when i is zero. (posting this as a comment and not an answer because fixing this typo won't completely solve your problem) Commented Dec 14, 2017 at 13:44
  • You need some way to tell your replacing script that the n'th occurrence of "-" translates to the n-1 index in x and just replace the occurrence with the value it finds on x[n-1]. A simple counter should do if you match occurrences to list indexes. Commented Dec 14, 2017 at 13:46

1 Answer 1

1

Try this instead:

i = (x for x in ['1', '2'])

with open("test.txt") as fin, open("result.txt", "w") as fout:
    for line in fin:
        if line.startswith('-'):
            fout.write(line.replace('-', '\nuse {}\ngo\n'.format(next(i))))
        else:
            fout.write(line)
Sign up to request clarification or add additional context in comments.

6 Comments

I think it would be best to do fout.write(line.replace('-', '\nuse {}\ngo\n'.format(str(x[i-1])))), he may want the value from x.
You can open the files with one with block: with open("test.txt", "r") as fin, open("result.txt", "w") as fout:
Like it better now?
I'd use f'\nuse {next(i)}\ngo\n' as this super fancy feature of Python 3.6 makes code more beautiful (IMO), but your solution works with every version of modern Python, so it's probably better. But I think that it's worth to say, that both original code and yours would throw some exceptions in case if count of '-' characters in file and your generator/list would have different length (there would be more '-' chars than items in generator).
@erhesto next() also takes default arguments. So one could write next(i, 'NaN') for example for bulletproofing. As long as there are is you would get those and when you run out, it will just give 'NaN'
|

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.