Dan
Dan

Reputation: 1587

not sure why my python loop isn't working

I have some text files (just using two here), and I want to read them in to Python and manipulate them. I'm trying to store lists of strings (one string for each word, one list each file).

My code currently looks like this: (files are named m1.txt and m2.txt)

dict={'m1':[],'m2':[]}

for k in files:        
with open(k,'r') as f:
        for line in f:
            for word in line.split():
                for i in range (1,3):
                    dict['m'+str(i)].append(word)

This code ends up combining the words in both text files instead of giving me the words for each file separately. Ultimately I want to read lots of files so any help on how to separate them out would be much appreciated!

Upvotes: 1

Views: 72

Answers (2)

mba12
mba12

Reputation: 2792

You were opening each list repeatedly while processing each individual file by alternative i values in the final for loop.

Try something like this:

dict={'m1':[],'m2':[]}

for i, k in enumerate(files):        
    with open(k,'r') as f:
        for line in f:
            for word in line.split():
                dict['m'+str(i+1)].append(word)

I've left your code "as is" but the comment above regarding not using language keywords is important.

Upvotes: 1

stevieb
stevieb

Reputation: 9296

This example dynamically fetches the file name (without the extension) and uses it to denote where in the dict we're working:

files = ['m1.txt', 'm2.txt'];
file_store = {'m1':[],'m2':[]}

for file in files:
    prefix = (file.split(r'.'))[0]
    with open(file, 'r') as f:
        for line in f:
            for word in line.split():
                file_store[prefix].append(word)

Upvotes: 1

Related Questions