0

I am trying to have my script be able to take in an arbitrary number of file names as command line arguments. In Unix, it is possible to use the '*' key to represent any character. For example,

ls blah*.txt 

will list every file with blah at the beginning and txt at the end.

I need something like this for my python script.

python myscript.py blah*.txt

Is this possible? and if it is, how can it be done?

1
  • 1
    Windows or Linux? In windows you have a more complex solution involve 2 lines of code. In Linux, this is already supported directly and trivially. See sys.argv Commented Aug 24, 2010 at 18:00

5 Answers 5

3
import sys

for arg in sys.argv[1:]:
  print arg

In Unix-land, the shell does the job of glob-expanding the commandline arguments, so you don't need to do it yourself. If you're processing a bunch of files in sequence, you might also look at the fileinput module, which works like Perl's "magic ARGV" handle and the -n and -i flags. It lets you loop over every line of every file named on the commandline, optionally moving the file to a backup name and opening stdout to the original name of the file, which lets you do something simple like:

import fileinput

for line in fileinput.input(inplace = True, backup = '.bak'):
  print fileinput.filelineno() + ": " + line

to add the line number to the beginning of every line of every file on the commandline, while saving the originals as filename.bak.

Sign up to request clarification or add additional context in comments.

Comments

1

Thats why you have sys.argv (and dont forget to import sys) It will return all your blah*.txt as a list of filenames

1 Comment

Hmmmm I did not know it could handle it. Thanks!
0

I think you want to use glob.

Comments

0

There is also fnmatch for when you don't want to have to worry about the path.

Comments

0
import sys, glob
files = reduce(lambda x, y: x + y, (glob.glob(x) for x in sys.argv[1:]))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.