简体   繁体   中英

efficient way of reading attributes of a file in python

I have a class whereby I am reading a file which has attributes such as width and height in the format

width 50
height 60

i want to read the file such that I create instances as I read the file eg self.width = 50 and self.height = 60 however, I can't find an efficient way to do this, any solutions?

this is my current code at the moment

f = open(filename, "r")
width = f.readline().split()
self.width = width[1]
# You can have it all on 1 line, or instances on each, i.e.
# width 50
# height 60
# or
# # This is the one this solution handles
# width 50 height 60
# width 20 height 10

results = []

f = open(filename, "r")
lineString = f.readline()

while lineString != None:
    line = lineString.split()
    values = {}
    for i in range(0, len(line), 2):
        values[line[i]] = int(line[i + 1]) # Integer, primarily for your case
    results.append(values)
    lineString = f.readline()

print(values)

What this is doing is reading each of the values in a line, the first is the name and the second is the value (third, fourth, etc.).

You can alter the code so it merges all the lines together using results[i].update(results[i+1]) iteratively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM