0

I am a novice to python scripting. I have a script that I am hoping to run on all files in a directory. I found very helpful advice in this thread. However, I am having difficulty in determining how to format the actual script so that it retrieves the filename of the file that I want to run the script on in the command prompt, i.e. "python script.py filename.*" I've tried my best at looking through the Python documentation and the forums in this site and have come up empty (I probably just don't know what keywords I should be searching).

I am currently able to run my script on one file at a time, and output it with a new file extension using the following code, but this way I can only do one file at a time. I'd like to be able to iterate over the whole directory using 'GENE.*':

InFileName = 'GENE.303'

InFile = open(InFileName, 'r') #opens a pipeline to the file to be read line by line

OutFileName = InFile + '.phy'

OutFile = open(OutFileName, 'w')

What can I do to the code to allow myself to use an iteration through the directory similar to what is done in this case? Thank you!

2 Answers 2

1

You are looking for:

import sys
InFileName = sys.argv[1]

See the documentation.

For something more sophisticated, take a look at the optparse and argparse modules (the latter is preferable but is only available in newer versions of Python).

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

Comments

0

You have quite a few options to process a list of files using Python:


You can use the shell expansion facilities of your command line to pass more filenames to your script and then iterate the command line arguments:

import sys

def process_file(fname):
    with open(fname) as f:
        for line in f:
            # TODO: implement
            print line

for fname in sys.argv[1:]:
    process_file(fname)

and call it like:

python my_script.py * # expands to all files in the directory

You can also use the glob module to do this expansion:

import glob

for fname in glob.glob('*'):
    process_file(fname)

Comments

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.