python printing each character in new line
Question: I'm trying to print lines and replace words in lines of a text/html file but
not able to do so because python (2.7) is reading it character by character.
What am I doing wrong?

Here is the code and output:

    
    
    import sys
    
    infile = open('filenmae').read()
    
    for line in infile:
        print line
    

The output I should get (only first line displayed here):

    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    

The output I'm getting:

    
    
    <
    !
    D
    O
    C
    T
    Y
    P
    E
    .
    .
    .
    


Answer: You are looping over a single string, which yields individual characters.

Don't read the file in one go, just loop over the file object:

    
    
    with open('filename') as infile:
        for line in infile:
            print line
    

I used the file as a context manager here as well (`with open(..) as
localname`); Python will now automatically close the file for you when the
`with` block is exited.

Looping over the file object reads lines as needed, avoiding reading the whole
file into memory.

Other alternatives are to read the file in one go as separate lines with the
[`file.readlines()`
method](http://docs.python.org/2/library/stdtypes.html#file.readlines):

    
    
    infile = open('filename').readlines()
    

or to split the read data with
[`str.splitlines()`](http://docs.python.org/2/library/stdtypes.html#str.splitlines):

    
    
    infile = open('filename').read().splitlines()
    

