Phil Thomas
Phil Thomas

Reputation: 21

Construct a filename from some of the arguments passed to a python script

I have inherited a python script which scans a website and outputs the results to a generic filename 'scanresult.txt'.

output1 = open("scanresult.txt","w",encoding='utf-8')

It is called with arguments

E.g.

python3 sv15.py -vdr "microsoft" -prod "windows_server_2019" or python3 sv15.py -key "Chrome" etc.

I have been asked, can we change it so that the filename becomes whatever the argument values passed in are separated by -

So microsoft-windows_server_2019.txt or chrome.txt

The code has these possible arguments in total and we don't know which ones the user will enter.

# Add the arguments to the parser
ap.add_argument("-key", "--keyword",
   help="first operand")
ap.add_argument("-vdr", "--vend",
   help="second operand")
ap.add_argument("-prod", "--product",
   help="3rd operand")
ap.add_argument("-ver", "--version",
   help="4th operand")
ap.add_argument("-pds", "--pub_st_dt",
   help="5th operand")
ap.add_argument("-pde", "--pub_en_dt",
   help="6th operand")
ap.add_argument("-mds", "--mds_st_dt",
   help="7th operand")
ap.add_argument("-mde", "--mds_en_dt",
   help="8th operand")

I thought

output_fname = '-'.join(args.values())

output1 = open(output_fname,"w",encoding='utf-8')

would do it but I get

Phils-MBP:Downloads pt$ python3 sv15.py -vdr "Juniper" -prod "ex4600"
Traceback (most recent call last):
  File "/Users/pt/Downloads/sv15.py", line 55, in <module>
    output_fname = '-'.join(args.values())
TypeError: sequence item 0: expected str instance, NoneType found

Upvotes: 2

Views: 60

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

You were close. You need to make sure you don't take an argument which is None:

output_fname = '-'.join(filter(None, args.values()))

or more explicitly

output_fname = '-'.join(arg for arg in args.values() if arg)

Keep in mind that, as correctly pointed out by JeanLColombo in the comments, this directly relies on user input which is a source for some concerns:

  • Some OS have a limit on file name length
  • Some OS do not allow certain characters in file names

Your code will need to take this into consideration, and handle the exception that will be raised during the creation of the file.

Upvotes: 2

Related Questions