简体   繁体   中英

Replacing string in txt file with content of another txt file (regular expressions)

I have two files: "invoiceencoded.txt"(base64 code) and "invoice.txt". I want to replace the word 'INPUT' in the second text file with the base64 code of the first text file. The purpose is to loop over the specific path for multiple examples of those, but that doesn't matter. I have the following code:

import re
import os
for f_name in os.listdir('C:/..'):
     if f_name.endswith('encoded.txt'):
         fin = open(f_name, "rt")
         filedata = fin.read()
         with open(f_name[:-11]+".txt", 'r+') as f:
                text = f.read()
                text = re.sub('INPUT', filedata, text)
                f.seek(0)
                f.write(text)
                f.truncate()

The 'INPUT' string is concatenated as 'abcINPUTdef'. However, instead of giving me

"abc base64code def", I get:

"abc base64code

def"

Does anyone know how to remove this line break?

Thanks in advance

Probably the line break is at the end of your base64 string in invoiceencoded.txt .

I'd suggest that you remove those line breaks and rerun your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM