-1

I have a dictonary like

list1={'ab':10,'ba':20,'def':30}. 

Now my input file contains :

ab def
ba ab

I have coded:

    filename=raw_input("enter file:")
    f=open(filename,'r')
    ff=open(filename+'_value','w')
    for word in f.read().split(): 
    s=0
    if word in list1:
        ff.write(word+'\t'+list1[word]+'\n');
        s+=int(list1[word])
    else:
        ff.write(word+'\n')
     ff.write("\n"+"total:%d"%(s)+"\n") 

Now I want my output file to contain:

ab 10
def 30
total: 40

ba 20
ab 10
total: 30

Am not able to loop it for each line. How should I do it? I tried a few variations using f.readlines(), f.read(), and tried looping once, then twice with them. But I cannot get it right.

charvi
  • 211
  • 1
  • 5
  • 16

3 Answers3

2

Instead of giving the answer right away, Let me give you a gist of what you ask:

To read the whole file:

f = open('myfile','r')
data = f.read()

To loop through each line in the file:

for line in data:

To loop through each word in the line:

    for word in line.split():

Use it wisely to get what you want.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
1

You need to make 2 loops and not only one:

filename = raw_input("enter file:")
with open(filename, 'r') as f, open(filename + '_value','w') as ff:
    # Read each line sequentially
    for line in f.read(): 
        # In each line, read each word
        total = 0
        for word in line.split():
            if word in list1:
                ff.write("%s\t%s\n" % (word, list1[word]))
                total += int(list1[word])
            else:
                ff.write(word+'\n')

        ff.write("\ntotal: %s\n" % total)   

I have also cleaned a little bit your code to be more readable. Also see What is the python "with" statement designed for? if you want to understand the with block

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
1
 with open("in.txt","r") as f:
    with open("out.txt","w") as f1:
        for line in f:
            words = line.split() # split into list of two words
            f1.write("{} {}\n".format((words[0]),list1[words[0]]))  # write first word plus value
            f1.write("{} {}\n".format((words[1]),list1[words[1]])) # second word plus value
            f1.write("Total: {}\n".format((int(list1[words[0]]) + int(list1[words[1]])))) # finally add first and second and get total
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321