Unable to save text file using while loop

Viewed 74

it saving a text file but the file was empty please help me, I think the error happen in the while loop? I already try for loop but it result in infinite loop

with open('F:\\datamining\\Textmining\\Coded\\newlist.txt') as fp:
    
    line  = fp.readline()
    cnt=1
    f=open('F:\\datamining\\Textmining\\Coded\\Lastlist.txt','w')
    while line:
        data=line.strip()
        if data in words :
            print(data)
            f.write(data+"\n")
        line=fp.readline()
        cnt += 1
1 Answers

I think the problem is that you should close the second file after writing. That can be done either with f.close() at the end of the writing loop, or with another indented context manager, that closes the file when exiting.

Solution with f.close():

with open('F:\\datamining\\Textmining\\Coded\\newlist.txt') as fp:
    
    line  = fp.readline()
    cnt=1
    f=open('F:\\datamining\\Textmining\\Coded\\Lastlist.txt','w') as f:
    while line:
        data=line.strip()
        if data in words :
            print(data)
            f.write(data+"\n")
        line=fp.readline()
        cnt += 1
    f.close()

Solution with the context manager:

with open('F:\\datamining\\Textmining\\Coded\\newlist.txt') as fp:
    
    line  = fp.readline()
    cnt=1
    with open('F:\\datamining\\Textmining\\Coded\\Lastlist.txt','w') as f:
        while line:
            data=line.strip()
            if data in words :
                print(data)
                f.write(data+"\n")
            line=fp.readline()
            cnt += 1

Related