Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open files given as command line arguments in python? [closed]

I want my .py file to accept file I give as input in command line. I used the sys.argv[] and also fileinput but I am not getting the output.

like image 549
Ram Avatar asked Nov 26 '11 17:11

Ram


People also ask

How do I open a file from command line in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do you access command line arguments in Python?

To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.

How do I open command line arguments?

option. You can test command line arguments by running an executable from the "Command Prompt" in Windows or from the "DOS prompt" in older versions of Windows. You can also use command line arguments in program shortcuts, or when running an application by using Start -> Run.

How do you pass a file path as an argument in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.


1 Answers

If you will write the following script:

#!/usr/bin/env python

import sys

with open(sys.argv[1], 'r') as my_file:
    print(my_file.read())

and run it, it will display the content of the file whose name you pass in the first argument like that:

./my_script.py test.txt

(in the above example this file will be test.txt).

like image 62
Tadeck Avatar answered Oct 14 '22 16:10

Tadeck