Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a suggestion to deal with files, I suppose the pattern you search is a whole line (there is nothing more on the line than the pattern and the pattern fits on one line).</p> <pre class="lang-py prettyprint-override"><code>line = ... # What to match input_filepath = ... # input full path output_filepath = ... # output full path (must be different than input) with open(input_filepath, "r", encoding=encoding) as fin \ open(output_filepath, "w", encoding=encoding) as fout: pattern_found = False for theline in fin: # Write input to output unmodified fout.write(theline) # if you want to get rid of spaces theline = theline.strip() # Find the matching pattern if pattern_found is False and theline == line: # Insert extra data in output file fout.write(all_data_to_insert) pattern_found = True # Final check if pattern_found is False: raise RuntimeError("No data was inserted because line was not found") </code></pre> <p>This code is for Python 3, some modifications may be needed for Python 2, especially the <code>with</code> statement (see <a href="http://docs.python.org/2.7/library/contextlib.html#contextlib.nested" rel="nofollow">contextlib.nested</a>. If your pattern fits in one line but is not the entire line, you may use <code>"theline in line"</code> instead of <code>"theline == line"</code>. If your pattern can spread on more than one line, you need a stronger algorithm. :)</p> <p>To write to the same file, you can write to another file and then move the output file over the input file. I didn't plan to release this code, but I was in the same situation some days ago. So here is a class that insert content in a file between two tags and support writing on the input file: <a href="https://gist.github.com/Cilyan/8053594" rel="nofollow">https://gist.github.com/Cilyan/8053594</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload