[英]How do I make my program so that the user can specify a file name?
I initially wrote a program that would read a file containing text, then would read each line and send it to the output file. 我最初编写了一个程序,该程序将读取包含文本的文件,然后读取每一行并将其发送到输出文件。 Now I am trying to make it so that I can allow the user to specify the file name on the command line and if the user doesn't specify a name, prompt them for one.
现在,我试图这样做,以便允许用户在命令行上指定文件名,如果用户未指定名称,则提示他们输入一个。 Any Idea how to do this?
任何想法如何做到这一点?
#Allow the user to enter the input and output file names
inputFileName = input("Input file name: ")
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()
Use argparse 使用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)
Then you call it with python program.py --file doc.txt
然后使用
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()
The way you are reading each line is really strange, I would suggest something like this 您阅读每一行的方式真的很奇怪,我建议这样
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
If you want to be able to call something like this: 如果您希望能够这样调用:
python program_name outputFileName
then 然后
from sys import argv
try:
outputFileName = argv[1]
except IndexError:
outputFileName = input("Output file name: ")
Also, I'm not sure if this was intentional, but your code doesn't actually write anything to outfile. 另外,我不确定这是否是故意的,但是您的代码实际上并未向outfile写入任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.