pythonpython-3.11

My Python program outputs vertically unexpectedly


I'm learning the Python programming language with the book "Self-taught Programmer" and just really starting out. no idea or knowledge previously so I'm currently stuck on working with files. I'm learning with Python311.

Trying to replicate the below codes from the book "Self-taught programmer"

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)

Output in book:

Hello from Python!

But mine (with same syntax) prints

H
e
l
l
o
 
f
r
o
m
 
P
y
t
h
o
n
!

Solution

  • When you use my_file.read(), without specifying a parameter, it reads the entire content of the file as a single string. Then, when you iterate over this string with "for line in my_file.read():", it iterates over each character of the string, not each line of the file.

    I believe that what you want to achieve is to read the file line by line and print each line. Here's the code for this:

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