从python中的命令行参数获取文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14360389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:11:22  来源:igfitidea点击:

getting file path from command line argument in python

python

提问by

Can anyone guide me how can I get file path if we pass file from command line argument and extract file also. In case we also need to check if the file exist into particular directory

如果我们从命令行参数传递文件并提取文件,任何人都可以指导我如何获取文件路径。如果我们还需要检查文件是否存在于特定目录中

python.py /home/abhishek/test.txt

get file path and check test.txt exist into abhishek folder.

获取文件路径并检查 test.txt 是否存在于 abhishek 文件夹中。

I know it may be very easy but I am bit new to pytho

我知道这可能很容易,但我对 pytho 有点陌生

回答by eumiro

import os
import sys

fn = sys.argv[1]
if os.path.exists(fn):
    print os.path.basename(fn)
    # file exists

回答by ATOzTOA

Use this:

用这个:

import sys
import os

path = sys.argv[1]

# Check if path exits
if os.path.exists(path):
    print "File exist"

# Get filename
print "filename : " + path.split("/")[-1]

回答by Ph03n1x

I think the most elegant way is to use the ArgumentParserThis way you even get the -hoption that helps the user to figure out how to pass the arguments. I have also included an optional argument (--outputDirectory).

我认为最优雅的方法是使用ArgumentParserThis way 你甚至可以获得-h帮助用户弄清楚如何传递参数的选项。我还包含了一个可选参数 ( --outputDirectory)。

Now you can simply execute with python3 test.py /home/test.txt --outputDirectory /home/testDir/

现在你可以简单地执行 python3 test.py /home/test.txt --outputDirectory /home/testDir/

import argparse
import sys
import os

def create_arg_parser():
    """"Creates and returns the ArgumentParser object."""

    parser = argparse.ArgumentParser(description='Description of your app.')
    parser.add_argument('inputDirectory',
                    help='Path to the input directory.')
    parser.add_argument('--outputDirectory',
                    help='Path to the output that contains the resumes.')
return parser


if __name__ == "__main__":
    arg_parser = create_arg_parser()
    parsed_args = arg_parser.parse_args(sys.argv[1:])
    if os.path.exists(parsed_args.inputDirectory):
       print("File exist")

回答by nijm

Starting with python 3.4 you can use argparsetogether with pathlib:

从 python 3.4 开始,您可以将argparsepathlib一起使用:

import argparse
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("file_path", type=Path)

p = parser.parse_args()
print(p.file_path, type(p.file_path), p.file_path.exists())