user1038662
user1038662

Reputation: 69

How to extract filenames from cmd input in python

I'm running a python program compiled on windows which receives files as input but have problems when I'm passing file names.

foo.py:

def main():
  args = sys.argv[1:]
  for i in args:
    print i

But when I compile and call it from the command line

\python foo.py *.html

It directly gives me the result of *.html which I hope to see a list of matching strings.

Can anyone hep plz:)

Upvotes: 2

Views: 199

Answers (2)

NPE
NPE

Reputation: 500327

Using the glob module will allow you to form paths correctly.

Upvotes: 0

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73608

You need to use something called glob. For a single filename what you are doing is fine. But if you want to loop through a file pattern, then use glob. It's basically a regex for files

import glob

glob.glob('*.html') #return all html files in curr dir
glob.glob('*')     # lists all files in the current directory python is running in
glob.glob('*.jpg')   # returns all jpeg images
glob.glob('[a-z]????.*')    # lists all files starting with a letter, followed by 4 characters (numbers, letters) and any ending.

So in your case -

import glob
def main():
   args = sys.argv[1:]
   for file in glob.glob(args):
       print i

Upvotes: 4

Related Questions