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

1

21

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.

Schuh answered 26/11, 2011 at 17:31 Comment(5)
You 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.Theorist
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.Schuh
I was doing this program in my VM machine (ubuntu) so I could not copy paste it in my windows machine.Schuh
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.)Theorist
@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()Schuh
L
43

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

Lubberly answered 26/11, 2011 at 17:41 Comment(3)
@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.