DEV Community

Discussion on: All You Need To Know About Context Managers In Python

Collapse
 
incrementis profile image
Akin C.

Hello Jerry Ng,

thanks for your article.
I am currently learning python for my upcoming studies.
I've read your code examples and coded them at the same time.
I noticed that the first snippet of code only worked when
'data = f.read ()' is removed.

I understand that this article is not intended for beginners, but it still has increased my knowledge of python a bit 🤓!

Collapse
 
jerrynsh profile image
Jerry Ng

Hey Akin! Good catch!

It was using w only which stands for Write-only. Instead, we should use w+ if we want to allow Read and Write operations.

I've updated it to be:

with open('hello.txt', 'w+') as f:
    data = f.read()
    f.write('Hello Python!')
Enter fullscreen mode Exit fullscreen mode