Reputation: 57
My list is not functioning properly because it is created as ["'carrots, 'tomatoes', 'lettuce'"]
rather than ['carrots, 'tomatoes', 'lettuce']
I have a text file with 'carrots, 'tomatoes', 'lettuce'
written on one line, and this is how I am writing it into my list:
veggie_list =[]
x = open('veggies.txt','r')
for item in x:
veggie_list.append(item)
Upvotes: 2
Views: 135
Reputation: 196
You can convert the list into the string and replace " with space then use eval it will return you list
veggie_list =[]
x = open('veggies.txt','r')
for item in x:
veggie_list.append(item)
veggie_list = eval(str(veggie_list).replace('"',''))
Upvotes: 1
Reputation: 10430
Try this (Assuming you have multiple lines in your text file):
veggie_list = []
with open('veg.txt','r') as x:
for item in x:
veggie_list.extend(item.replace("'", "").split(','))
print(veggie_list)
Outputs:
['carrots', ' tomatoes', ' lettuce']
If you are only interested in the first line of your text file:
veggie_list = []
with open('veg.txt','r') as x:
veggie_list = x.read().replace("'","").split(',')
print(veggie_list)
One Liner in Python using list comprehension:
with open('veg.txt','r') as x:
print([j for i in x for j in i.replace("'","").split(',')])
EXPLANATION (For the first code):
You need to first remove the single quote marks from the line you have read ("'carrots', 'tomatoes', 'lettuce'"
) from the file. You can use replace() method of str
object. This method returns a copy of modified string and it doesn't change the original string.
After that, you should be left with str "carrots, tomatoes, lettuce"
. Now, I have used split() method to divide the whole string into individual strings using ","
as delimiter.
This method returns a list ['carrots', ' tomatoes', ' lettuce']
.
Upvotes: 1
Reputation: 9
I have an idea, but it depends and the way that your text file is written:
veggies = []
veggie_list = []
x = open('veggies.txt','r')
for item in x:
veggie.append(item)
for i in veggies:
veggie_list.append(i)
This is probably that case. Your outer parentheses might signal that ["'carrots, 'tomatoes', 'lettuce'"]
is probably just one item inside the list. If you iterate it twice, it might work. Hope it helps
Upvotes: 0
Reputation: 45
You inserting the String "'carrots, 'tomatoes', 'lettuce'". What I think you want to do is:
text = x.read()
text = text.replace("'","")
enter code here
veggie_list = text.split(",")
Upvotes: 1