My requirement is to read a text file from command line interface, fetch the data in it & use it in further code. But, I'm unable to do it. If i use the line1, then It is throwing error1 If line 1 is commented, It is throeing error2
I also tried with args.file in line1.
Can you help me in taking the file as input and use file methods to modify it?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", type=argparse.FileType('rt'))
args = parser.parse_args()
#f = open("file", "r") ---line1
lines = file.readlines()
file.close()
print(lines[0].rstrip('\n'))
print(lines[1])
error 1:
py parser.py demo.txt
Traceback (most recent call last):
File "C:\Users\nthotapalli\PycharmProjects\pythonProject\parser.py", line 6, in <module>
f = open("file", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'file'
error 2:
py parser.py demo.txt
Traceback (most recent call last):
File "C:\Users\nthotapalli\PycharmProjects\pythonProject\parser.py", line 9, in <module>
lines = file.readlines()
AttributeError: 'str' object has no attribute 'readlines'