0

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'
0

3 Answers 3

1

To call readlines() you need to have a file like object.

To have a file like object you need to call open(<filename>)

So in your case it would be:

file = open(args.file)
lines = file.readlines()

Or with context manager:

with open(args.file) as file:
    lines = file.readlines()
Sign up to request clarification or add additional context in comments.

Comments

0

Pass the path of the file as an argument and then open it, that way you can access the object's methods.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="File path", default="/tmp/file.txt")
args = parser.parse_args()

file = open(args.file, "r")
lines = file.readlines()

print(f"Number of lines: {len(lines)}")
print(f"Fist line: {lines[0]}")

Comments

0

args is the Namespace produced by the parser. You need to fetch the values from that, not use a string "file", or uninitialized variable file. And 2nd be aware of what the FileType produces.

parser = argparse.ArgumentParser()
parser.add_argument("file", type=argparse.FileType('rt'))
args = parser.parse_args()

add

print(args)   # to see what the parser found
file = args.file   # 

then you can do:

lines = file.readlines()
file.close()

The problem with:

f = open("file", "r")

is you are trying open a file called "file".

With FileType, args.file will be a already opened file, which you can then read and close. No further open is needed, or even possible.

Alternatively you could have defined:

parser.add_argument("file")

in which case args.file will a string, which you can use in the open

file = open(args.file)

or better yet

with open(args.file) as file:
     lines = file.readlines()

2 Comments

Thankyou for all, whoever answered. I tried all the ways that were listed above. But it was not working. The error is : FileNotFoundError: [Errno 2] No such file or directory: 'args.file'. But there exist a file in the path.
Are you using open('args.file')?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.