1

My python code is called within a bash script, and also the python script requires an input argument from bash loop. But I wasn't sure the best way to do this. Here's my attempt:

bash code:

cat filelList.txt | while read i;#file1List.txt stores file names
do
python script.py $i > $i.txt
done

python bit that i'm not sure of:

file = sys.argv[0] # not sure about this
in = open(file)
for line in iter(in): # not sure about this
    do something.......

Does anyone know the best way to write these 3 python lines? Thank you

user27976
  • 903
  • 3
  • 17
  • 28

1 Answers1

1

Why not do everything in python? Assuming you have a folder where you have to process each file:

import sys
import os

assert os.path.isdir(sys.argv[1])
listing = os.listdir(sys.argv[1])

for filename in listing:
    with open(sys.argv[1]+"/"+filename,'r') as f:

        for line in f:
            #do something                                                                                                                                                                                                                    
            pass

Alternatively if you have a file containing a list of other files to process:

import sys
import os

assert os.path.isfile(sys.argv[1])

with open(sys.argv[1]) as filelist:
    filenames = [line.strip() for line in filelist]
    for filename in filenames:
        if not os.path.isfile(filename):
            print >> sys.stderr , "{0} is not a valid file".format(filename)
            break
        with open(filename,'r') as f:
            for line in f:
                #do something                                                                                                                                                                                                                
                pass
igon
  • 3,016
  • 1
  • 22
  • 37