Search code examples
pythonfor-loopfilewriterfile-readunidecoder

A substite for "for looping" in text files


from unidecode import *
reader = open("a.txt",'w')
def unite():
    for line in reader:
        line = unidecode(line)
        print (line)
unite()

Now, I get an error saying for looping is not allowed in write mode. Is there any other way, I can modify each individual line like so, that it can be converted using unidecode?


Solution

  • You could hold it all in memory.

    from unidecode import *
    
    reader = open("a.txt",'w')
    lines = reader.readlines()
    def unite(lines):
        for line in lines:
            line = unidecode(line)
            print (line)
    unite()
    

    You could also use a temp file.

    from unidecode import *
    import os
    
    reader = open('a.txt','r')
    temp = open('~a.txt', 'w')
    for line in reader():
        line = unidecode(line)
        temp.write(line)
    reader.close()
    temp.close()
    
    os.remove('a.txt')
    os.rename('~a.txt', 'a.txt')