1

I have a Python script that inputs all words from a file and sorts them in order:

with open(raw_input("Enter a file name: ")) as f :
     for t in sorted(i for line in f for i in line.split()):
           print t

But instead of asking every time for the input file I would like to choose the input file with a "-i" and save the output file with a "-o", this way:

python myscript.py -i input_file.txt -o output_file.txt 

and BTW, how to save the output on a target file?

2 Answers 2

4

This should do it:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='infile',
                    help="input file", metavar='INPUT_FILE')
parser.add_argument('-o', dest='outfile',
                    help='output file', metavar='OUTPUT_FILE')
args = parser.parse_args()

with open(args.infile, 'r') as infile:
    indata = infile.read()

words = indata.split()
words.sort()

with open(args.outfile, 'w') as outfile:
    for word in words:
        outfile.write('{}\n'.format(word))

argparse is a built-in module for parsing command-line options. It does all the work for you.

$ ./SO_32030424.py --help
usage: SO_32030424.py [-h] [-i INPUT_FILE] [-o OUTPUT_FILE]

optional arguments:
  -h, --help      show this help message and exit
  -i INPUT_FILE   input file
  -o OUTPUT_FILE  output file
Sign up to request clarification or add additional context in comments.

8 Comments

All good, but it gives me an error: I do think that in this way is not creating a file: Traceback (most recent call last): line 15, in <module> with open(args.outfile) as outfile: IOError: [Errno 2] No such file or directory: 'dest.txt'
Whoops! I didn't specify the mode; fixed.
Thank you. I tried to add 'w' but it didn't worked. What else have you changed? I want to learn.
@FrancescoMantovani, that's all I changed. Can you paste your code that didn't work even with 'w' on a pastebin?
too late. Probably it was caused by no come before 'w'
|
0

To get started on your parameters, take a look at sys.argv.

To write into an output file, use the write mode "w", and .write() to it.

For the latter there are definitely good tutorials out there.

2 Comments

sys.argv takes only bare parameters as a list but did not deal with flags like -i.
Yeah, you can write that yourself though. Or use argparse.

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.