On Mar 22, 2:06 pm, Bradley Hintze <bradle...@aggiemail.usu.edu> wrote: > I just started with argparse. I want to simply check the extension of > the file that the user passes to the program. I get a ''file' object > has no attribute 'rfind'' error when I use > os.path.splitext(args.infile). Here is my code. > > import argparse, sys, os > > des = 'Get restraint definitions from probe.' > parser = argparse.ArgumentParser(description=des) > parser.add_argument('infile', nargs='?', type=argparse.FileType('r')) > # parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), > # default=sys.stdout) > > args = parser.parse_args() > # print args.infile.readlines() > print basename, extension = os.path.splitext(args.infile)
Because you specified type=argparse.FileType('r') argparse has created args.infile as a file object (e.g. open('/some/path/data.dat', 'r')), not as a string containing the path. So type(args.infile) == type(file) and args.infile.readlines() returns the contents of that file. If you wish to check the file extension of the path in question I suggest you remove type=argparse.FileType('r'), argparse will create args.infile as a string containing that path. To open the file call open(args.infile, 'r'), this will return the file object. -- http://mail.python.org/mailman/listinfo/python-list