Reputation: 797
I have a set of text files and i am trying to read it into a single list.but when i execute my code
def get_documents():
path1 = "D:/set/"
texts=[]
listing1 = os.listdir(path1)
for file in listing1:
with open(path1+file,'r') as f:
lines = f.read().splitlines()
texts.append(lines)
print texts
I am getting output as list of lists
[['Wanna see Riya Somani :) wish lyf olso moment lyk end half galfrnd... :) '], ['Worst book Mr. Chetan Bhagat.. Plz better stori ']]
How can i get it as a single list?
Upvotes: 1
Views: 97
Reputation: 104474
I believe instead of this:
texts.append(lines)
Do this:
texts.extend(lines)
Upvotes: 5
Reputation:
as you might have guessed, splitlines() returns a list, so when you put the result into another list (in your case, texts), you will have a list containing some lists. so a way to reach your desired result is to use:
new_list = [item for sub_list in texts for item in sub_list]
new_list would be your desired list
Upvotes: 0