DJ29
DJ29

Reputation: 31

How to I split items from a txt file using multiple arguments

My txt file looks like this:

chihuahua
japanese spaniel
maltese dog, maltese terrier, maltese

I'm looking for an

output  = ['chihuahua', 'japanese spaniel', 'maltese dog', 'maltese terrier', 'maltese'] 

I'm essentially looking to split the items first by (newline) and then by a comma

I've tried using:

dog_n = [line.rstrip('\n') for line in open('dognames.txt')]

and I get the following output:

['chihuahua', 'japanese spaniel', 'maltese dog, maltese terrier, maltese']

length of list above is 3

I'm looking for a length 5 by splitting all the words

Upvotes: 0

Views: 62

Answers (1)

Nouman
Nouman

Reputation: 7303

You have to replace commas with newlines \n and use split to get a list:

dog_n = open('dognames.txt', "r").read().replace(",", "\n").split('\n')

Output:

['chihuahua', 'japanese spaniel', 'maltese dog', ' maltese terrier', ' maltese']

Edit:

If you are willing to close file then use:

with open('dognames.txt', "r") as f:
    dog_n = f.read().replace(",", "\n").split('\n')

Upvotes: 3

Related Questions