Day #50 - read(), readline() and other methods

Day #50 - read(), readline() and other methods

ยท

3 min read

Introduction

Welcome to my 50th blog post on the Python journey. On day 50, I learned about reading and writing in the Python file. In this blog, I will discuss the readline() and writelines() functions in Python. Now Let's dive into more details and understand File handling in Python.

So let's get started......

readline() method

  • It reads single lines from the file

  • To read multiple lines we need to use loops

  • This method reads all the lines from a file and returns them as a string

  • To use the content as an integer or another datatype, we need to typecast the string returned.

Example -

f = open('myfile.txt', 'r')
while True:
    line = f.readline()
    if not line:
        break
    print(line)

writelines() method

  • This method writes a sequence of strings in a file.

  • The sequence that you want to write can be any iterable object, such as a list or a tuple.

Example -

f = open('myfile.txt', 'w')
lines = ['line 1\n', 'line 2\n', 'line 3\n']
f.writelines(lines)
f.close()

Note: - The writelines() method does not add a new line character between the string. If you want to add new lines, you can use a loop to write each string separately

It is a good practice to close the file, once you are done with it

f = open('myfile.txt', 'w')
lines = ['line 1', 'line 2', 'line 3']
for line in lines:
    f.write(line + '\n')
f.close()

Resources Used

You can watch the video of Day#50 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. On day 50, I learned about reading and writing into a file using readline() and writelines() function in Python. I also wrote a bunch of code to practice these concepts.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #50

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย