python-3.x - 使用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 - 读取 CSV 后具有奇怪值的 Spark 数据帧
- php - 在 Wordpress 中仅显示一篇最新文章
- mongodb - mongodb聚合函数并根据条件返回结果
- oracle - Oracle dbms_aq.dequeue
- python - 我无法在 pip install 上安装模块,它给出红色文本错误
- flutter - parse_server_sdk 和 parse_server 有什么区别?
- html - CSS - 如何在表单输入中每 3 个字符放置一个空格?
- c# - 不存在 LayerHost 的 Blazor Fluent UI 下拉问题
- javascript - 转到给定的 URL(如果我们不在那里),显示表单并滚动到它
- javascript - 重构验证处理和消息传递