-1

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
!
1
  • 3
    my_file.read() returns a string, not a list of lines. Either use for line in my_file: or for line in my_file.readlines() Commented May 10, 2024 at 14:44

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.