[Tutor] Pass arguments from bash script to embedded python script

Mats Wichmann mats at wichmann.us
Fri Oct 25 11:08:04 EDT 2019


On 10/25/19 5:24 AM, Stephen P. Molnar wrote:

> What a great and gracious response.
> 
> Thanks to the help from this list, I have achieved success. Here is my 
> code:

>> import os
>> import glob
>> import numpy as np
>>
>> fileList = []
>>
>>
>> for files in glob.glob("*.log"):
>>     fileName, fileExtension = os.path.splitext(files)
>>     fileList.append(fileName)
>>
>> for filename in fileList:
>>     data = np.genfromtxt(filename+'.log', usecols=(1), skip_header=27, 
>> skip_footer=1, encoding=None)
>>     np.savetxt(filename+'-dG', data, fmt='%.15g', header=filename)

Cool... and that code looks concise and expressive - easy to figure out 
what it's doing and why, congratulations!

=== ===

Now, just a few comments, which you can safely ingore since you've 
gotten where you want to.

1. If you use a code checker on this, it's probably going to complain 
about this line:

fileName, fileExtension = os.path.splitext(files)

because you unpack the returned tuple from splitext into two variables, 
but you never use fileExtension.  Python has some syntax for indicating 
that you don't care about a variable, that's the single underscore by 
itself. So if you rewrote the line as:

fileName, _ = os.path.splitext(files)

you would be telling the code checker that you'll intentionally not be 
using the second element.

2. There's a cool new-ish module called pathlib which aims to be more 
expressive in working with, well, file paths.  It has its own methods 
for doing a glob, and for extracting the stem part of a filename (that 
is, without the extension), so the first loop could be rewritten like 
this - again, there's no *need* to do this.

import pathlib

p = Path('.')   # create Path object for this directory
for path in p.glob("*.log"):
     fileList.append(path.stem)


and then, seeing you have a loop where all it does is append to a list, 
you could rewrite that as a list comprehension - some of us find that 
notation more readable, though I know when I first learned about it I 
admit I didn't at first see how it was an improvement, now I do.

fileList = [path.stem for path in p.glob("*.log")]



More information about the Tutor mailing list