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.
Asked
Active
Viewed 8.2k times
21
-
5You question is not clear. It is unclear what your goal is, what output you expect, what you tried and how it falied. Instead of saying "I used the `sys.argv[]` and also `fileinput`", 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. – Sven Marnach Nov 26 '11 at 17:33
-
The task is I need to check if the given file containing strings is a valid email address. for ex: if there are four lines , I need to check if each line is a valid email address. However I was able to check that. I got the required output for the file I gave as input. I am trying to modify it to accept any file given as command line argument to the particular .py file so that it will take the file and check if that file has valid email addresses. – Ram Nov 26 '11 at 17:52
-
I was doing this program in my VM machine (ubuntu) so I could not copy paste it in my windows machine. – Ram Nov 26 '11 at 17:57
-
Both, `sys.argv` and `fileinput` 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.) – Sven Marnach Nov 26 '11 at 18:00
-
@SvenMarnach `import 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()` – Ram Nov 26 '11 at 18:34
1 Answers
41
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
).

Tadeck
- 132,510
- 28
- 152
- 198
-
-
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. – Ram Nov 26 '11 at 23:10
-