Reputation: 686
I want to make a list of words separated by comma from a text file(not csv file). For example, my text file contains the line as:
apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery
I want to make a list of each word as:
['apple','Jan 2001','shelter','gate','goto','lottery','forest','pastery']
All I could do is get the words as it is with the code below:
f = open('image.txt',"r")
line = f.readline()
for i in line:
i.split(',')
print i,
Upvotes: 0
Views: 10343
Reputation: 2236
content = '''apple, Jan 2001, shelter
gategoto, lottery, forest, pastery'''
[line.split(",") for line in content.split("\n")]
Upvotes: 0
Reputation: 10680
Input: image.txt
apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery
banana, Jul 2012, fig, olive
Code:
fp = open('image.txt')
words= [word.strip() for line in fp.readlines() for word in line.split(',') if word.strip()]
print(", ".join(words)) # or `print(words)` if you want to print out `words` as a list
Output:
apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery, banana, Jul 2012, fig, olive
Upvotes: 1
Reputation: 122112
>>> text = """apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery"""
>>>
>>> with open('in.txt','w') as fout:
... fout.write(text)
...
>>> with open('in.txt','r') as fin:
... print fin.readline().split(', ')
...
['apple', 'Jan 2001', 'shelter', 'gate', 'goto', 'lottery', 'forest', 'pastery']
Upvotes: 2
Reputation: 1734
This should work. Can also be simplified but you will understand it better this way.
reading = open("textfiles\example.txt", "r")
allfileinfo = reading.read()
reading.close()
#Convert it to a list
allfileinfo = str(allfileinfo).replace(',', '", "')
#fix first and last symbols
nameforyourlist = '["' + allfileinfo + '"]'
#The list is now created and named "nameforyourlist" and you can call items as example this way:
print(nameforyourlist[2])
print(nameforyourlist[69])
#or just print all the items as you tried in the code of your question.
for i in nameforyourlist:
print i + "\n"
Upvotes: 1
Reputation: 5373
Change your
f.readline()
to
f.readlines()
f.readline() will read 1 line and return a String object. Iterating over this will cause your variable 'i' to have a character. A character does not have a method called split(). What you want is to iterate over a list of Strings instead ...
Upvotes: 0
Reputation: 10288
Try this:
[i.strip() for i in line.split(',')]
Demo:
>>> f = open('image.txt', 'r')
>>> line = f.readline()
>>> [i.strip() for i in line.split(',')]
['apple', 'Jan 2001', 'shelter', 'gate', 'goto', 'lottery', 'forest', 'pastery']
Upvotes: 1