首页 > 解决方案 > 使用python复制文件并替换多个关键字

问题描述

我需要在运行时从下面的 Excel 表中读取每个 testId的 TestQuery 和 HiveOpFile,并且需要在 python 脚本中替换它们(我从另一个文件中复制了它们。)。我尝试了以下代码:

在此处输入图像描述

例如对于 TestID XXX-123

#have working code to read both columns data as per TestID.
HiveTestQL =  'Select UNIT, from_unixtime(unix_timestamp(EFFECTIVE_DATE,"yyyy-MM-dd HH24:mm:ss")) from Table1;' 
TargetFile =  'Z:/home/user/Result1.csv'

.

#file code which i am copying  HiveBeelineConn.py

import subprocess
from subprocess import PIPE, Popen


connection_url = "jdbc:hive2://axxxx.com:10000/xxxxxxxxprincipal=hive/_HOST@BDS.xxxxx.COM"
############To Update Query from excel################
sql = sql_q             
 
cmd1 = 'INSERT OVERWRITE  DIRECTORY "'+ exportDir + '/" ROW FORMAT DELIMITED FIELDS TERMINATED BY "'+ delimetedBy + '" ESCAPED BY \"\\\\\ " ' + nld + sql +";"
val = subprocess.check_output(hive_query, shell=True)

############To Update file name from excel################
opFile = hiveOpFile

代码我试图复制文件并替换字符串


with open('Z:\HiveBeelineConnToRun.py', 'wb+') as output, open('Z:\HiveBeelineConn.py', 'rb') as input:
    copyfileobj(input, output)
    output.close()

with open('Z:\HiveBeelineConnToRun.py', 'r') as output1:
    f_data = output1.read()
f_data = f_data.replace('sql_q', f"'{HiveTestQL}'" ).replace('hiveOpFile', f"'{TargetFile}'" )

with open('Z:\HiveBeelineConnToRun.py', 'w') as file:
    file.write(f_data)
    file.close()

上面的代码工作正常并创建一个 python 文件 HiveBeelineConnToRun.py 从 HiveBeelineConn.py 复制并替换值。在这里,我使用 3 with 语句仅替换一个文件中的 2 个字符串。有没有更有效的方法来做到这一点?我尝试使用 For 循环,但结果为空文件。

with open('Z:\HiveBeelineConnToRun4.py', 'r+') as output1:
    f_data = output1.read()

    for line in f_data:
        new_line = line.replace('sql_q', HiveTestQL)
        new_line = line.replace('hiveOpFile', TargetFile)
        output1.write(new_line)
    output1.close()

标签: python-3.xre

解决方案


推荐阅读