Search code examples
arrayspython-2.7filestorewords

how store text files from directory in 2d arrays in python?


I want store my files from a folder in 2d arrays it means:words are my columns and for each file there is on row. this is my code but words store in array wrongly,what should I do? for example: file 1:hello python file 2:bye c++ I expect in row 1 store hello in column 1 and python in column 2 and in row 2 store bye in column 1 and c++ in column 2

j=0
i=0
adress=""
import os, sys

# Open a file
path = 'E:/corpus'   
dirs = os.listdir( path )

# This would print all the files and directories      
for files in dirs:
    print files
    j=0
    i=i+1
    my=""

    adress='E:/corpus/'+files
    with open(adress, 'r') as myfile:
        for myline in myfile:
            for word in myline.split(" "):
                my=my+" "+word

    data=my.split(" ")
    for mydata in data:
        mylist[i][j]=mydata
        j=j+1

Solution

  • I found answer finally,this cod store 100 txt file form a folder in 100 rows of an array and the words of each file are columns of this array.

    n=100
    mylist=[]
    tempstring=""
    row=0
    
    
    import os, sys
    
    # Open a file
    path = 'E:\corpus'   
    dirs = os.listdir( path )
    
    # This would print all the files and directories      
    for files in dirs:
    
    
        print files
    
    
        adress='E:/corpus/'+files
        with open(adress, 'r') as myfile:
            for myline in myfile:
                for word in myline.split(" "):
    
                    tempstring=tempstring+" "+word
    
        a=0
        temparray=tempstring.split(" ")
        for i in xrange(row,row+1):
    
    
            mylist.append([])
    
            for data in temparray:
    
                mylist[i].append(data)
                a=a+1
        if(a==len(temparray)):
            row=row+1
            tempstring=""