18
votes

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.

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

4

4 Answers

27
votes
import os
import sys

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

Starting with python 3.4 you can use argparse together with pathlib:

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())
8
votes

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

Now you can simply execute with 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")
4
votes

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]