파일의 모든 단어를 입력하고 순서대로 정렬하는 Python 스크립트가 있습니다.
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
그러나 매번 입력 파일을 요청하는 대신 "-i"로 입력 파일을 선택하고 "-o"로 출력 파일을 저장하려고합니다.
python myscript.py -i input_file.txt -o output_file.txt
및 BTW, 출력을 대상 파일에 저장하는 방법은 무엇입니까?
이렇게해야합니다.
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
명령 줄 옵션을 구문 분석하기위한 내장 모듈입니다. 그것은 당신을 위해 모든 일을합니다.
$ ./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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다