python在新行中打印每个字符

dsa*_*uce 0 python python-2.7

我正在尝试打印行并在text/html文件的行中替换单词但由于python(2.7)逐字符地读取它而无法这样做.我究竟做错了什么?

这是代码和输出:

import sys

infile = open('filenmae').read()

for line in infile:
    print line
Run Code Online (Sandbox Code Playgroud)

我应该得到的输出(这里只显示第一行):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

<
!
D
O
C
T
Y
P
E
.
.
.
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 9

您循环遍历单个字符串,从而生成单个字符.

不要一次读取文件,只是循环遍历文件对象:

with open('filename') as infile:
    for line in infile:
        print line
Run Code Online (Sandbox Code Playgroud)

我在这里使用该文件作为上下文管理器(with open(..) as localname); 现在,Python将在with退出块时自动为您关闭文件.

循环遍历文件对象根据需要读取行,避免将整个文件读入内存.

其他替代方法是使用以下file.readlines()方法将文件一次性读取为单独的行:

infile = open('filename').readlines()
Run Code Online (Sandbox Code Playgroud)

或者将读取的数据拆分为str.splitlines():

infile = open('filename').read().splitlines()
Run Code Online (Sandbox Code Playgroud)