A question on the creation of list of lists

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Apr 22 13:01:23 EDT 2015


----- Original Message -----
> From: "subhabrata banerji" <subhabrata.banerji at gmail.com>
> To: python-list at python.org
> Sent: Wednesday, 22 April, 2015 6:18:30 PM
> Subject: A question on the creation of list of lists
> 
> Dear Group,
> 
> I am trying to open a bunch of files from a directory and trying to
> put the results in list of lists that is to say,
> 
> that is to say,
> I have a list of file names of a directory, I want to read each one
> of them.
> After reading each one of them, I want to put the results of each
> file in a list.
> These lists would again be inserted to create a list of lists.
> 
> to do this I am trying to write it as follows:
> 
> list_of_files = glob.glob('C:\Python27\*.*')
>     print list_of_files
>     list1=[]
>     list2=[]
>     list_N=[list1,list2]
>     for i,j in zip(list_of_files,list_N):
>         print i,j
>         x1=open(i,"r").read()
>         x2=j.append(x1)
>     all_sent=list_N
>     print all_sent
> 
> Am I doing anything wrong? If any one may kindly suggest?
> Is there any smarter way to do it? I am using Python2.7+
> on MS-Windows 7 Professional Edition.
> Apology for any indentation error.
> 
> Regards,
> Subhabrata Banerjee.

I'm not sure about what you're trying to do. But here are a couple of remarks:

1/ Your file pattern search will not get files that do not have any dot in their name or will get directory that have a dot in their name. Here's a better way of filtering files:

import glob
import os

filenames = [item for item in glob.glob('C:\Python27\*') if os.path.isfile(item)]

2/ the append method returns always None

x2=j.append(x1) will bind x2 to None. That is probably something you don't want. However you never use x2, so you can simply write:

j.append(x1)

3/ your for loop seems broken, but I'm not sure as I don't really know what you're trying to do. Here's a simple code that you may start from:

filenames = [item for item in glob.glob('C:\Python27\*') if os.path.isfile(item)]
content = []
for filename in filenames:
  with open(filename, 'r') as f:
    content.append(f.read())

all_sent = [filenames, content] 

You should end up with a list of list, the first list is the file names, the second their content:

with 2 files file1 file2 you should get
all_sent : [['file1', 'file2'], [content1, content2]]

Is it what you're trying to do ?

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list