1

I have this code:

with open("text2.txt", 'r') as file:        
    for cats in file:
        if "blue" in cats: 
            print (cats)

the text2.txt file looks like this:

blue cat 3 
blue cat 2 
blue cat 5 
red cat 2 
green cat 2 
blue cat 3
yellow cat 5 

I want to get a list that looks like this:

["blue cat 3, blue cat 2, blue cat 5, blue cat 3"] 

And the "make your list by hand" is not a option for me, I'm dealing with a big file, so this is not a solution for my problem:

mylist = ["blue cat 3, blue cat 2, blue cat 5, blue cat 3"]
6
  • do you want only blue cats Commented Mar 9, 2016 at 13:19
  • yes i only want blue cats Commented Mar 9, 2016 at 13:20
  • Can't you append to a list while iterating over the lines ? Commented Mar 9, 2016 at 13:21
  • What if there is another blue cats below the rest. Do you want to include all blue cats lines, or just the ones that appear right on top of each other. Commented Mar 9, 2016 at 13:21
  • I acctully dont know how append works, I'm a newbie. Commented Mar 9, 2016 at 13:22

6 Answers 6

4

This can be very easily done with a list comprehension. You are simply looping over each line in the file and only keeping the ones that contain 'blue' in it:

with open("text2.txt", 'r') as file:
    n = [i.strip() for i in file if 'blue' in i.lower()]

print(n)

Will output:

['blue cat 3', 'blue cat 2', 'blue cat 5', 'blue cat 3']

To expand on how the above works and relate it to your code:

You actually were not far off at all. The only thing you were missing in your solution was to actually create a list and append to it:

So, create an empty list:

blue_cats = []

Then keep your code as as, however change the print (cats) for appending to your. Notice I used strip(). This will remove the \n that remains in the string due to it being in the file and you probably don't want it. Finally, as an added bonus to make sure you always find 'blue', you want to force lower case by using lower() on the string you are searching against:

blue_cats = []
with open("text2.txt", 'r') as file:        
    for cats in file:
        if "blue" in cats.lower(): 
            blue_cats.append(cats.strip())
Sign up to request clarification or add additional context in comments.

2 Comments

List comprehension faster than appending. Use the top part of the answer if you want to do it in the most effient way out of the two.
@JohnSmith That is correct. The second part of the answer was to provide the OP with a deeper understanding of what was happening and what they needed to change in their code to get it to work.
1

If you can edit the code you've presented above, you can simply add a list

blue_cats = []
with open("text2.txt", 'r') as file:        
    for cats in file:
        if "blue" in cats: 
            blue_cats.append(cats)

Comments

1

The following approach should help:

with open("text2.txt", 'r') as f_input:
    output = [row.strip() for row in f_input if row.startswith("blue cat")]

print(', '.join(output))

This will print:

blue cat 2, blue cat 5, blue cat 3

Comments

0

Try creating an array and then appending the values you want to that array:

blue_cats=[]
with open("text2.txt", 'r') as file:        
    for cats in file:
        if "blue" in cats: 
            blue_cats.append(cats.strip())
print(blue_cats)

Comments

0
with open("text2.txt", 'r') as file:
    blue_cats = [cats.strip() for cats in file if "blue" in cats.lower()]

Comments

0

technically, none of the answers so far results in the requested output.

The OP requested the output to be this:

["blue cat 3, blue cat 2, blue cat 5, blue cat 3"] 

which is a one element list, containing a "comma-&-space"-separated-string, containing only the 'blue cats' from the input file

I suspect that this was a typo, then again maybe not.

So to correctly answer the question, here some code:

with open("text2.txt", 'r', encoding='utf_8') as openfile:
    cats = [line.strip() for line in openfile if 'blue' in line.lower()]
mystring = ""
for cat in cats:
    mystring += ', ' + cat
mylist = []
mylist.append (mystring[2:])

mylist now contains the requested output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.