28

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

1
  • 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. Commented Oct 24, 2022 at 8:22

5 Answers 5

35
import os
import sys

fn = sys.argv[1]
if os.path.exists(fn):
    print os.path.basename(fn)
    # file exists
Sign up to request clarification or add additional context in comments.

2 Comments

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
@user765443 - yes, you can have a look at the argparse module.
16

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

Comments

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

Comments

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]

Comments

1
import sys
from pathlib import Path

# Check if the argument is passed
if len(sys.argv) != 2:
    print("Usage: python sample.py <log_file_name>")
    sys.exit(1)

# Get the log file name
log_file_name = sys.argv[1]

# Check if the file exists
log_file_path = Path(log_file_name)
if not log_file_path.exists():
    print(f"Error: File '{log_file_name}' not found.")
    sys.exit(1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.