Reputation: 80
I have write this code to replace multiple lines in a txt file, in order to correct a SQL query.
import fileinput
with fileinput.FileInput('C:/Users/thiago.ribeiro/Desktop/Documentos Gerais/Hard_Time6.txt', inplace=True, backup='.bak') as file:
for line in file:
print(line.replace("""END
UNION ALL""", """END
UNION ALL )
GROUP BY AC,
TYPE_SERIES,
PN,
QTY_PER_ACFT
UNION ALL
"""), end='')
This is a sample of SQL query in TXT file:
SELECT B.AC,
B.AC_TYPE ||'-'|| B.AC_SERIES AS "TYPE/SERIES",
CASE WHEN C.PN = NULL THEN 'DK120' ELSE 'DK120' END AS "PN",
C.PN AS "PN_ACFT_INVENTORY",
COUNT (DISTINCT C.SN) AS "Nº OF COMPONENTS INSTALLED",
CASE WHEN C.PN IN ('DK120', 'ELP-362D', '266E5542-00') THEN 2 ELSE 2 END AS "Qty per ACFT",
CASE WHEN COUNT (DISTINCT C.SN) = 2 THEN 'OK' ELSE 'DISCREPANCY FOUND' END AS "ACFT Inventory CHECK"
FROM ODB.AC_MASTER B
LEFT JOIN ODB.PN_INVENTORY_DETAIL C
ON C.INSTALLED_AC = B.AC
AND C.PN IN ('DK120',
'ELP-362D', '266E5542-00')
LEFT JOIN (SELECT AC,
DEFECT_DESCRIPTION,
CASE WHEN DEFECT_DESCRIPTION LIKE '%REDELIVERY%' THEN 'REDELIVERY' ELSE 'REDELIVERY' END AS "STATUS"
FROM ODB.DEFECT_REPORT
WHERE DEFECT_TYPE = 'OOS'
AND DEFECT_DESCRIPTION LIKE '%REDELIVERY%'
UNION ALL
SELECT AC,
DEFECT_DESCRIPTION,
CASE WHEN DEFECT_DESCRIPTION LIKE '%CHECK%' THEN 'HEAVY_CHECK' ELSE 'HEAVY_CHECK' END AS "STATUS"
FROM ODB.DEFECT_REPORT
WHERE DEFECT_TYPE = 'OOS'
AND DEFECT_DESCRIPTION LIKE '%CHECK%'
AND STATUS = 'OPEN') D
ON D.AC = B.AC
WHERE B.AC_TYPE ||'-'|| B.AC_SERIES = 'ATR72-600'
AND B.STATUS = 'ACTIVE' AND D.STATUS IS NULL
GROUP BY B.AC,
B.AC_TYPE ||'-'|| B.AC_SERIES,
C.PN,
CASE WHEN C.PN = NULL THEN 'DK120' ELSE 'DK120' END
The problem is that it seems that the python code is not replacing lines breaks.
Upvotes: 0
Views: 294
Reputation: 1581
I think you shouldn't read your file line by line for this problem. It is not that python does not replace line breaks, but as each line ends at line break, you can't have any line matching your multi-lines content.
You could instead read whole file with content=file.read()
and perform the substitution on content
.
Upvotes: 2