1

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!

3
  • 1
    What do you mean by combining? You only declared one dictionary, so of course they're all going to go into that dictionary. Are you trying to create multiple dictionaries, one for each file? Commented Dec 6, 2016 at 20:37
  • 1
    also you're appending words theoretically from m1.txt into dict['m2'] Commented Dec 6, 2016 at 20:39
  • 4
    also bad practice to use a built in word dict as a variable Commented Dec 6, 2016 at 20:39

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks for the help - I'll change the name of my dictionary as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.