26

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

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Some tips after running into an issue where I know that the script works and that the files exists. If the current directory in the terminal is `dir1` and you are trying to run a script that lives in `dir2` and you are passing relative path argument for your script `dir3` like `python3 dir2/myscript.py dir3` then: `dir3` should be relative to current directory `dir1` and not relative to the dir where the script lives `dir2`. – nakakapagpabagabag Oct 24 '22 at 08:22

4 Answers4

33
import os
import sys

fn = sys.argv[1]
if os.path.exists(fn):
    print os.path.basename(fn)
    # file exists
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • Thanks for providing input . just want to add one thing. Can we get file name without sys.argv[1]. As per existing framework They suggest me not to use sys.argv –  Jan 16 '13 at 14:19
  • 1
    @user765443 - yes, you can have a look at the `argparse` module. – eumiro Jan 16 '13 at 14:22
14

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())
nijm
  • 2,158
  • 12
  • 28
11

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")
Mahmoud Mabrok
  • 1,362
  • 16
  • 24
Ph03n1x
  • 794
  • 6
  • 12
4

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]
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117