简体   繁体   中英

Creating a list from a file

I'm creating a horoscope where I have a file with different qualities and 4-5 sentences with different statements regarding each quality. The qaulities are separated with a blank line. I want to save them into a list called qualities, where qualities[0] contains the sentences regaring the first quality, qualities[1] contains the sentences regarding the second and so on.

My code:

class Horoscope:

    def __init__(self, filename):
        self.qualities = list()
        file = open(filename, 'rU')
        i = 0
        for line in file:
            row= line.strip().split('/')
            if len(row) >= 2:
                self.qualities[0+i] = row
            else:
                i += 1
        file.close() FILENAME= 'horoscope.txt'

horoscope= Horoscope(FILENAME)

print(horoscope.qualities)

Unfortunally, all that is printed is "[ ]"... Does anyone know why? Thanks!

I'm surprised self.qualities[i] did not raise an IndexError. That suggests that len(row) is never >= 2 . However, if it were, you should use append instead:

class Horoscope:
    def __init__(self, filename):
        self.qualities = list()
        with open(filename, 'rU') as f:
            for line in f:
                row = line.strip().split('/')
                if len(row) >= 2:
                    self.qualities.append(row)

FILENAME= 'horoscope.txt'
horoscope= Horoscope(FILENAME)
print(horoscope.qualities)

Note that this does not replicate the logic of your original code. It appends every row for which len(row) >= 2 . You original code does something more complicated, sometimes overwriting at the same index, sometimes advancing the index. Do you really want that? If so, what do you want to place in the list at the locations where the index is simply advanced? None ? Something value have to be placed at every index... (You can't have a list with values only at, say, the second and fifth index. A list of length 5 has to have 5 values.)

It almost looks like your code could be simplified to:

class Horoscope:
    def __init__(self, filename):
        with open(filename) as fin:
            self.qualities = [line.strip() for line in fin if '/' in line]

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