Search code examples
pythonpython-2.7args

Arg parse inside with Python 2.7


I would need to insert variables for the input file in a 'with' function while reading/writing in it. Here is the part of code that I am currently interested in:

import argparse

parser=argparse.ArgumentParser(description="My script")
parser.add_argument('-i','--input',help='Input log file name',required=True)
parser.add_argument('-o','--output',help='Desired name for the Excel file',required=True)
parser.add_argument('-s','--sheet',help='Desired name of the Excel sheet(Default: Sheet1)',default='Sheet1',required=False)
args=parser.parse_args()

with open('%s',%args.input, 'r') as file :
  filedata = file.read()
filedata = filedata.replace('destination', 'destination          xxx')
with open('%s',%args.input, 'w') as file:
  file.write(filedata)

'%s',%args.input, 'r' is not valid, but I would need something that does this thing. The same for 'w'. Any ways for a workaround?

Many thanks,

Romain


Solution

  • Just found the error:

    import argparse
    
    parser=argparse.ArgumentParser(description="My script")
    parser.add_argument('-i','--input',help='Input log file name',required=True)
    parser.add_argument('-o','--output',help='Desired name for the Excel file',required=True)
    parser.add_argument('-s','--sheet',help='Desired name of the Excel sheet(Default: Sheet1)',default='Sheet1',required=False)
    args=parser.parse_args()
    
    with open('%s' %args.input, 'r') as file :
      filedata = file.read()
    filedata = filedata.replace('destination', 'destination          xxx')
    with open('%s' %args.input, 'w') as file:
      file.write(filedata)