#!/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(argv[1]) as f: for line in f: # strip the new line character # print("before strip ...>", line) foo = line.rstrip('\n') print("after strip ...>", foo) # find the first non-whitespace # #i = len(foo) - len(foo.lstrip()) if (len(foo) != 0) and (foo[0] != '#'): lines.append(foo) f.close() print("------ before reading -------------") print(lines) print("------ done reading -------------") # iterate over lines and break into parts # print("------ starting parsing -------------") for line in lines: print("*> splitting: %s" % line) parts = line.split() print("...>") print(parts) print("...<") parts = line.split('=') print("***", parts[0], " = ", parts[1]) print("------ end of parsing -------------") # second method # print("------ second method -------------") print("------ second method -------------") print("------ second method -------------") for line in open(sys.argv[1],'r').readlines(): foo = line.rstrip('\n') print("2nd method: ", foo) print("..... end of second method .......") # third method # print("------ third method -------------") print("------ third method -------------") lines = [line.rstrip('\n') for line in open(sys.argv[1])] print("3rd method: ", lines) print("------ end of third method -------------") print(" ") print(" ") print(" ") #--- # 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] print("***>", lines) # close the file # f.close() print("------ end of fourth method -------------") # 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('#') print(parts) # 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