我有一个用于生成批处理文件的python代码,输入来自txt文件
def create_bat_file(lp=None):
with open(r"test.txt", "r+") as file:
currentDir = os.path.abspath(".")
data = file.readlines()
for line in data:
a = line.split('=')
b = a[0]
f = a[1]
bk = a[2]
reldat = a[3]
f= open("{}.bat".format(f),"w+")
f.write("@ECHO OFF\n")
f.write("SET lp="'"{}"'"\n".format(lp))
if b == "RB":
f.write("SET reldat="'"{}"'"".format(reldat))
if b == "RB":
f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
else:
f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
f.close()
test.txt文件的输入内容不足
RB=TEST14=https://test.com.org/rest/api/latest/queue/TEST-RR=2017-12-06
下面是输出
@ECHO OFF
SET lp="test"
SET reldate="2017-12-06
"C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
问题是何时创建批处理文件(TEST14.bat)
Wrong:
SET reldate="2017-12-06
"C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
在输出中,双引号结尾是下一行 它应该总是像
Correct:
SET reldate="2017-12-06"
C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
答案 0 :(得分:1)
line
的最后一个字符是换行符\n
。 reldat
的最后一个字符也是换行符。因此,就行:
f.write("SET reldat="'"{}"'"".format(reldat))
您最终在最后一个\n
之前添加了"
。
要解决此问题,您可以从\n
中剥离line
并在需要的地方添加缺失的一个:
def create_bat_file(lp=None):
with open(r"test.txt", "r+") as file:
currentDir = os.path.abspath(".")
data = file.readlines()
for line in data:
line = line[:-1] #### STRIP NEWLINE CHARACTER ####
a = line.split('=')
b = a[0]
f = a[1]
bk = a[2]
reldat = a[3]
f= open("{}.bat".format(f),"w+")
f.write("@ECHO OFF\n")
f.write("SET lp="'"{}"'"\n".format(lp))
if b == "RB":
f.write('SET reldat="{}"\n'.format(reldat)) #### ADD MISSING NEWLINE ####
if b == "RB":
f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
else:
f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
f.close()
我还自由地在字符串周围使用单引号,看起来好多了!