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.
How to open files given as command line arguments in python? [closed]
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
).
@Ram: I am glad it helped. Do you have any additional questions? –
Lubberly
No I have actually submitted the output and got a full score! thanks :) I did it with
sys.arg
but I got errors so did not know what mistake I was doing. After reading your post I learnt that sys.argv
accepts the command line arguments as array and that is why we use the indexing. –
Schuh Does this also work for files which are in different directories? –
Sedan
© 2022 - 2024 — McMap. All rights reserved.
sys.argv[]
and alsofileinput
", it would be better to show your actual code. Instead of saying "I am not getting the output," better show the output you get and the output you expect. – Theoristsys.argv
andfileinput
are possible solutions for this problem. We can't point out your mistake in using them because you didn't tell us what you tried. (Generally, it is best to edit your original question to clarify it.) – Theoristimport re def emailValidate(): emailPattern = re.compile("^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[]a-zA-Z]{2,6}$") f = file(sys.argv[1], 'r') lines = f.readlines()
– Schuh