1
import re
import os

MARKER = 'hello'
readFileData = "['\\n', '\\r', '\\0'];\nvar MONTH_TO_NUM = { jan: 0, feb: 1, mar: 2 };\n"
outFileBuffer ='updated file\nhello\n'

outFileBuffer = re.sub(MARKER, (readFileData + MARKER), outFileBuffer)

# output of re.sub doesn't preserve double slash \\
# outFileBuffer = "updated file\n['\n', '\r', '\x00'];\nvar MONTH_TO_NUM = { jan: 0, feb: 1, mar: 2 };\nhello\n"

destination = os.getcwd() + "test.txt"
with open(destination, "w") as f:
  f.write(outFileBuffer)

input.txt

var TERMINATORS = ['\n', '\r', '\0'];
var MONTH_TO_NUM = { jan: 0, feb: 1, mar: 2 };

Contents of input.txt are stored in readFileData variable after reading.

As soon as re.sub fn is used double forward slash are converted to single slash. Refer outFileBuffer comment.

When the buffer is written back to disk var TERMINATORS = ['\n', '\r', '\0']; seems to messed up, because outFileBuffer is not escaped properly.

How can escaped string be preserved while using re.sub method.

vito
  • 473
  • 1
  • 7
  • 17
  • 1
    Right, you need `re.sub(MARKER, readFileData + MARKER, outFileBuffer.replace('\\', '\\\\'))`. See [my answer](https://stackoverflow.com/a/56524477/3832970). – Wiktor Stribiżew Apr 08 '20 at 09:24
  • @WiktorStribiżew thanks. but it works with `readFileData = readFileData.replace('\\', '\\\\')` – vito Apr 08 '20 at 09:31
  • The point is that all backslashes in the dynamic string replacement patterns must be doubled in order to be literal backslashes. – Wiktor Stribiżew Apr 08 '20 at 09:38
  • @WiktorStribiżew yup `re.sub(MARKER, (readFileData + MARKER).replace('\\', '\\\\'), outFileBuffer).replace('\\', '\\\\')` – vito Apr 08 '20 at 10:09

0 Answers0