0

i have this piece of code:

asm = open(infile)
asmw = open(outfile, "w")
shutil.copyfile(infile, outfile)
for x in range(0, 8):
    xorreg.append("xor " +  reg[x] + ", " +  reg[x])
for line in asm:
    if any(s in line for s in xorreg):
    found += line.count(xorreg[x])
    print line

i want to write some text lines in the file right before "line" (the one printed) how can i do that?

Thanks

4
  • print "something else" ? Commented Dec 13, 2014 at 23:02
  • i mean, write in the file Commented Dec 13, 2014 at 23:03
  • but that way the line that i wanna write would be after the one i looked for, no? Commented Dec 13, 2014 at 23:12
  • I'll post an example Commented Dec 13, 2014 at 23:13

1 Answer 1

4

This script appends to every lien containing the string Gandalf a new string The greatest wizard of all times was:

# show what's in the file
with open("some_file.txt", 'r') as f:
    print f.read()

new_content = []
with open("some_file.txt", "r") as asmr:
    for line in asmr.readlines():
        if "Gandalf" in line:
            # we have a match,we want something but we before that...
            new_content += "The greatest wizard of all times was:"
        new_content += line

# write the file with the new content
with open("some_file.txt", "w") as asmw:
    asmw.writelines(new_content)

# show what's in the file now
with open("some_file.txt", 'r') as f:
    print f.read()
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for that. the problem is that i dont wanna show the file, im showing only the lines that contains some element of my xorreg[] array. and these elements are the ones that i want to write before
What do you mean by show? You don't have to show the file, this was just for anyone reading this to be clearer. You only need to re write the file, and when you encounter a row you want to add a line before, you need to add the new line and only than the original line.

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.