Using ConfigParser to read a file without section name

前端 未结 7 2172
星月不相逢
星月不相逢 2020-11-27 03:36

I am using ConfigParser to read the runtime configuration of a script.

I would like to have the flexibility of not providing a section name (there are s

7条回答
  •  鱼传尺愫
    2020-11-27 03:59

    The easiest way to do this is to use python's CSV parser, in my opinion. Here's a read/write function demonstrating this approach as well as a test driver. This should work provided the values are not allowed to be multi-line. :)

    import csv
    import operator
    
    def read_properties(filename):
        """ Reads a given properties file with each line of the format key=value.  Returns a dictionary containing the pairs.
    
        Keyword arguments:
            filename -- the name of the file to be read
        """
        result={ }
        with open(filename, "rb") as csvfile:
            reader = csv.reader(csvfile, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE)
            for row in reader:
                if len(row) != 2:
                    raise csv.Error("Too many fields on row with contents: "+str(row))
                result[row[0]] = row[1] 
        return result
    
    def write_properties(filename,dictionary):
        """ Writes the provided dictionary in key-sorted order to a properties file with each line of the format key=value
    
        Keyword arguments:
            filename -- the name of the file to be written
            dictionary -- a dictionary containing the key/value pairs.
        """
        with open(filename, "wb") as csvfile:
            writer = csv.writer(csvfile, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE)
            for key, value in sorted(dictionary.items(), key=operator.itemgetter(0)):
                    writer.writerow([ key, value])
    
    def main():
        data={
            "Hello": "5+5=10",
            "World": "Snausage",
            "Awesome": "Possum"
        }
    
        filename="test.properties"
        write_properties(filename,data)
        newdata=read_properties(filename)
    
        print "Read in: "
        print newdata
        print
    
        contents=""
        with open(filename, 'rb') as propfile:
            contents=propfile.read()
        print "File contents:"
        print contents
    
        print ["Failure!", "Success!"][data == newdata]
        return
    
    if __name__ == '__main__': 
         main() 
    

提交回复
热议问题