PYTHON get files from command line

2019-01-17 03:13发布

How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:

python code.py input.txt

so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a pretty vague question, but I don't really know how to explain it any better.

6条回答
\"骚年 ilove
2楼-- · 2019-01-17 03:34

Using argparse is quite intuitive:

import argparse
parser = argparse.ArgumentParser()                                               

parser.add_argument("--file", "-f", type=str, required=True)
args = parser.parse_args()

Now the name of the file is located in:

args.file

You just have to run the program a little differently:

python code.py -f input.txt
查看更多
相关推荐>>
3楼-- · 2019-01-17 03:37

A great option is the fileinput module, which will grab any or all filenames from the command line, and then give the contents to your script as though they were one big file.

import fileinput
for line in fileinput.input():
    process(line)

More information here.

查看更多
老娘就宠你
4楼-- · 2019-01-17 03:37

In addition to what is mentioned by the already existing answers, there is an other alternative relying on the use of Command Line Interface Creation Kit (Click). Its latest stable version by the time I posted this answer is version 6. The official documentation has examples on how to deal with files and pass them as command line arguments.

查看更多
萌系小妹纸
5楼-- · 2019-01-17 03:40
import sys
filename = sys.argv[-1]

This will get the last argument on the command line. If no arguments are passed, it will be the script name itself, as sys.argv[0] is the name of the running program.

查看更多
不美不萌又怎样
6楼-- · 2019-01-17 03:40

Command line parameters are available as a list via the sys module's argv list. The first element in the list is the name of the program (sys.argv[0]). The remaining elements are the command line parameters.

See also the getopt, optparse, and argparse modules for more complex command line parsing.

查看更多
smile是对你的礼貌
7楼-- · 2019-01-17 03:42

Just use the basic command raw_input

declare input file name as string

inFile = ""
inFile = raw_input("Enter the input File Name: ")

Now you can open the file by using with open(inFile,'w')

查看更多
登录 后发表回答