简体   繁体   English

用另一个txt文件的内容替换txt文件中的字符串(正则表达式)

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

I have two files: "invoiceencoded.txt"(base64 code) and "invoice.txt".我有两个文件:“invoiceencoded.txt”(base64 代码)和“invoice.txt”。 I want to replace the word 'INPUT' in the second text file with the base64 code of the first text file.我想用第一个文本文件的 base64 代码替换第二个文本文件中的“输入”一词。 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'. 'INPUT' 字符串连接为 'abcINPUTdef'。 However, instead of giving me然而,而不是给我

"abc base64code def", I get: “abc base64code def”,我得到:

"abc base64code "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 .换行符可能位于 invoiceencoded.txt 中 base64 字符串的末尾

I'd suggest that you remove those line breaks and rerun your script.我建议您删除这些换行符并重新运行您的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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