0

I have a python code which I am using to generate the batch file and the input is coming from txt file

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 file is having below input

CL=TEST14=https://test.com.org/latst/queue/TEST-R=2020-12-22

Below is the output

@ECHO OFF
SET lp="test"
SET reldate="2020-12-22
"C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR

Issue is when it creates the batch file (TEST14.bat)

Wrong:

SET reldate="2020-12-22
    "C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR 

in output the end double quote comes to the next line it should be always like

Correct:

SET reldate="2020-12-22"
C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR

1 Answer 1

2

The last character of line is the newline character \n. The last character of reldat is also the newline character. Therefore, on the line:

f.write("SET reldat="'"{}"'"".format(reldat))

You end up adding a \n before the last ".

To fix, you can strip the \n from line and add the missing one where it is needed:

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()

I also took the freedom to use single quotes around the string, it looks much better!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.