我的Python程序意外地垂直输出

问题描述 投票:0回答:1

我正在通过《自学程序员》一书学习 Python 编程语言,并且才真正开始。以前没有任何想法或知识,所以我目前一直在处理文件。我正在用Python311学习。

尝试复制《自学程序员》书中的以下代码

with open('my_file.txt','w') as my_file:
    my_file.write('Hello from Python!')

with open("my_file.txt", "r") as my_file:
    for line in my_file.read():
        print(line)

书中输出:

Hello from Python!

但是我的(具有相同语法)打印

H
e
l
l
o
 
f
r
o
m
 
P
y
t
h
o
n
!
python python-3.11
1个回答
1
投票

当您使用 my_file.read() 时,如果不指定参数,它会将文件的整个内容作为单个字符串读取。然后,当您使用“for line in my_file.read():”迭代此字符串时,它会迭代字符串的每个字符,而不是文件的每一行。

我相信你想要实现的是逐行读取文件并打印每一行。这是代码:

with open("my_file.txt", "r") as my_file:
    for line in my_file:
        print(line)
© www.soinside.com 2019 - 2024. All rights reserved.