如何制作程序以便用户指定文件名?

时间:2016-04-11 01:54:30

标签: python file

我最初写了一个程序,它将读取包含文本的文件,然后读取每一行并将其发送到输出文件。现在我正在努力使它能够允许用户在命令行上指定文件名,如果用户没有指定名称,则提示他们输入一个名称。任何想法怎么做?

$controller("myController", {myObject: myObject});

2 个答案:

答案 0 :(得分:1)

使用argparse

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--file', help='file path') #add --file to the args
args = parser.parse_args()

if not(args.file): #if they didn't specify a --file, prompt them
    file = input("Please enter file path?")
else:
    file = args.file #if they did specify file, make file what they specified in the cmd

print(file)

然后用python program.py --file doc.txt

调用它

根据您的具体情况编辑

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--input', help="input file")
parser.add_argument('--output', help="output file")
args = parser.parse_args()

if args.input:
    inputFileName = args.input
else:
    inputFileName = input("Input file name: ")

if args.output:
    outputFileName = args.output
else:
    outputFileName = input("Output file name: ")


#Open the input and output files
infile = open(inputFileName,"r")
outfile = open(outputFileName, "w")

#Define count
count=0

#Reads the input file and produces the output file
line = infile.readline()


while line != "":
    count = count+1
    print(count, line)
    line = infile.readline()

#Close the infile and the outfile    
infile.close()
outfile.close()

建议编辑

你阅读每一行的方式真的很奇怪,我会建议这样的事情

for line in infile: #loop through every line in infile
    outfile.write(line) #write this line to outfile
    print(line.rstrip("\n")) #print this line, but don't print the \n. that's why you were having multiple line breaks before

答案 1 :(得分:0)

如果您希望能够拨打以下内容:

python program_name outputFileName

然后

from sys import argv
try:
    outputFileName = argv[1]
except IndexError:
    outputFileName = input("Output file name: ")

另外,我不确定这是否是故意的,但你的代码实际上并没有向outfile写任何内容。