Home > OS >  how to pass file as argument & modify it in python script using argparse module?
how to pass file as argument & modify it in python script using argparse module?

Time:12-29

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'

CodePudding user response:

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

CodePudding user response:

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]}")

CodePudding user response:

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()
  • Related