#!/usr/bin/env python # import required modules # import os import sys # main: this is the main function of this Python # def main(argv): # first method # #lines = [] #with open(sys.argv[1]) as f: # for line in f: # foo = line.rstrip('\n') # if foo[0] != '#': # lines.append(foo) #f.close() #print(">>>", lines) # iterate over lines and break intp parts # #for line in lines: #print("*> splitting: %s" % line) #parts = line.split('.') #print("...") #print(parts) #print("...") #parts = line.split('=') #print("***", parts[0], " = ", parts[1]) # second method # #for line in open(sys.argv[1],'r').readlines(): # print("2nd method: ", line) # third method # #lines = [line.rstrip('\n') for line in open(sys.argv[1])] #print("3rd method: ", lines) #--- # let's put all this together and write code that opens a file, # detects if the first nonwhitespace character is a '#', # and if not, splits the line and gets the name and value #--- # open the file with error checking # try: f = open(sys.argv[1]) except: print("***> error opening file... exiting...") exit(-1) with f: # read the file into memory # lines = [line.rstrip('\n') for line in f] # close the file # f.close() # loop over the data and only process the lines that don't # begin with a comment character # for line in lines: # remove spaces and newline chars # line = line.replace(' ', '').replace('\n', '').replace('\t', '') # check if the line starts with comments: if it does, skip it, else # process it # if line.startswith('#') or len(line) == 0: pass else: # split the line by an inline comment character # parts = line.split('#') # split the first part of the line into name/value pairs # values = parts[0].split('=') # display the result # print('**> name = ', values[0], '***> value = ', values[1]) # begin gracefully # if __name__ == "__main__": main(sys.argv) # # end of file