简体   繁体   English

python在换行中打印每个字符

[英]python printing each character in new line

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. 我正在尝试打印行并替换text / html文件行中的单词,但无法执行此操作,因为python(2.7)正在逐个字符地读取它。 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
.
.
.

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 ); 我也在这里使用文件作为上下文管理器( with open(..) as localname ); Python will now automatically close the file for you when the with block is exited. 现在,当退出with块时,Python会自动为您关闭文件。

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 : 其他替代方法是使用file.readlines()方法单独读取一行文件:

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

or to split the read data with str.splitlines() : 或使用str.splitlines()拆分读取的数据:

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

You should try file.readlines() instead as follows: 您应该尝试使用file.readlines()代替,如下所示:

infile = open('filename').readlines()
for line in infile:
    print line

This loops over each line rather than each character in the file. 这会循环遍历每一行,而不是文件中的每个字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM