Francesco Mantovani
Francesco Mantovani

Reputation: 12227

How use input and output file in Python

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?

Upvotes: 1

Views: 1518

Answers (2)

Cyphase
Cyphase

Reputation: 12012

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

Upvotes: 4

Berserker
Berserker

Reputation: 1112

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.

Upvotes: 0

Related Questions