user765443
user765443

Reputation:

getting file path from command line argument in python

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

Upvotes: 28

Views: 118730

Answers (4)

Ph03n1x
Ph03n1x

Reputation: 844

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")

Upvotes: 11

nijm
nijm

Reputation: 2218

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

Upvotes: 16

eumiro
eumiro

Reputation: 212885

import os
import sys

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

Upvotes: 35

ATOzTOA
ATOzTOA

Reputation: 35950

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]

Upvotes: 4

Related Questions