Home > Enterprise >  Why isn't python doing it's job on every line?
Why isn't python doing it's job on every line?

Time:04-29

I want to get the info from every line, parse it to a dictionary with the content split. Whenever I run it, it works great for the first line and then stops.

(Content looks like:
A: aasdflkjasdf;aj
B: basdfalksdfla...)


flower_file = "flowers.txt"
flower_dict = {}

flowerlist=[]
with open(flower_file, 'r') as flowers:
    flowerlist = flowers.readline()

for line in flowerlist.splitlines():
    key, value = line.split(':')
    flower_dict[key] = str(value)
    continue

CodePudding user response:

You're only reading one line, so you're only processing one line. Python's doing what you told it to.

There is no need to read the whole file into a list anyway. Just iterate over the file:

with open(flower_file, 'r') as flowers:
    for line in flowers:
        key, value = line.split(':')
        flower_dict[key] = value

You also don't need the continue so I've removed that, and also no need to convert a string to a string so I took that out too.

This breaks if there are any lines in the file that don't have exactly one colon. You can make it more robust by using partition() rather than split():

with open(flower_file, 'r') as flowers:
    for line in flowers:
        key, _, value = line.partition(':')
        if value:
            flower_dict[key] = value
        else if not line.strip():   # allow whitespace-only line
            print("invalid line:", line)

CodePudding user response:

Add an s. You ask for one line, you get one line.

flowerlist=[]
with open(flower_file, 'r') as flowers:
    flowerlist = flowers.readlines()

And you probably don't need to splitlines() because flowerlist will be a list of lines.

  • Related