Read/ Write File in Python with Examples – 5 Minutes Tutorial – My programming school

This tutorial covers the next subject – Python Write File/Read File. It describes the syntax of the writing to a file in Python. Also, it explains the right way to write to a textual content file and supplies a number of examples for assist.

For writing to a file in Python, you would wish a few features akin to Open(), Write(), and Read(). All these are built-in Python features and don’t require a module to import.

There are majorly two sorts of information you might have to work together with whereas programming. One is the textual content file that comprises streams of ASCII or UNICODE (UTF-8) characters. Each line ends with a newline (“n”) char, a.okay.a. EOL (End of Line).

Another sort of file is named binary that comprises machine-readable knowledge. It doesn’t have, so-referred to as line as there isn’t any line-ending. Only the applying utilizing it could find out about its content material.

Anyways, this tutorial will strictly inform you to work with the textual content information solely.

Python Write File Explained with Examples

Let’s start this tutorial by taking over the primary name required to put in writing to a file in Python, i.e., Open().

Open File in Python

You first should open a file in Python for writing. Python supplies the built-in open() perform.

The open() perform would return a deal with to the file if it opened efficiently. It takes two arguments, as proven under:

''' Python open file syntax '''
 file_handle = open("file_name", "access_mode")

The first argument is the identify or path of the file (together with file identify). For instance – sample_log.txt or /Users/john/house/sample_log.txt.

And the second parameter (elective) represents a mode to open the file. The worth of the “access_mode” defines the operation you need to carry out on it. The default worth is the READ solely mode.

# Open a file named "sample_log.txt" 
# It rests in the identical listing as you might be working in. 
file_handle1 = open("sample_log.txt")

# Let's open the file from a given path
file_handle2 = open("/Users/john/home/sample_log.txt")

File Open Modes

It is elective to go the mode argument. If you don’t set it, then Python makes use of “r” because the default worth for the entry mode. It implies that Python will open a file for learn-solely objective.

However, there are a complete of six entry modes obtainable in python.

  • “r” –  It opens a textual content file for studying. It retains the offset in the beginning of the file. If the file is lacking, then it raises an I/O error. It can be the default mode.
  • “r+” –  It opens the file for each READ and WRITE operations. It units the offset in the beginning of the file. An I/O error happens for a non-existent file.
  • “w” –  It opens a file for writing and overwrites any present content material. The deal with stays in the beginning of the info. If the file doesn’t exist, then it creates one.
  • “w+” –  It opens the file for each READ and WRITE operations. Rest, it really works the identical because the “w” mode.
  • “a” –  It opens a file for writing or creates a brand new one if the file not discovered. The deal with strikes to the top (EOF). It preserves the prevailing content material and inserts knowledge to the top.
  • “a+” –  It opens the file for each READ and WRITE operations. Rest, it really works the identical because the “a” mode.

Check out a couple of examples:

# Open a file named "sample_log.txt" in write mode
# It rests in the identical listing as you might be working in.
file_handle1 = open("sample_log.txt", "w")

# Open the file from a given path in append mode
file_handle2 = open("/Users/john/home/sample_log.txt", "a")

Write File in Python

Python supplies two features to put in writing right into a textual content file: Write() and Writelines().

1. write() – Let’s first use write() for writing to a file in Python. This perform places the given textual content in a single line.

''' Python write() perform '''
 file_handle.write("some text")

But, first, open any IDE and create a file named “sample_log.txt” for our take a look at. Don’t make every other modifications to it.

Please be aware – If you attempt to open a file for studying and it doesn’t exist, then Python will throw the FileNotFoundError exception.

To edit this file out of your Python program, we’ve given the next code:

# A easy instance - Python write file
file_handle = open("sample_log.txt","w") 

file_handle.write("Hello Everyone!") 
file_handle.write("It is my first attempt to write to a file in Python.") 
file_handle.write("I'll first open the file and then write.") 
file_handle.write("Finally, I'll close it.") 


We’ve opened the file in “w” mode, which implies to overwrite something written beforehand. So, after you open it and see its content material, you’ll discover the brand new textual content in 4 totally different traces.

2. writelines() – The writelines() perform takes an inventory of strings because the enter and inserts every of them as a separate line in one go. You can test its syntax under:

''' Python writelines() perform '''
 file_handle.writelines([str1, str2, str3, ...])

Append File in Python

You additionally must know the right way to append the brand new textual content to an present file. There are two modes obtainable for this objective: a and a+.

Whenever you open a file utilizing one among these modes, the file offset is ready to the EOF. So, you’ll be able to write the brand new content material or textual content subsequent to the prevailing content material.

Let’s perceive it with a couple of traces of code:

We’ll first open a file in “a” mode. If you run this instance the primary time, then it creates the file.

# Python Append File in "a" mode Example
fh = open("test_append_a.txt", "a")
fh.write("Insert First Linen")
fh.write("Append Next Linen")

So far, two traces have been added to the file. The second write operation signifies a profitable append.

Now, you’ll see the distinction between the “a” and “a+” modes. Let’s attempt a learn operation and see what occurs.

fh.learn() # io.UnsupportedOperation: not readable

The above line of code would fail because the “a” mode doesn’t permit READ. So, shut it, open, after which do a learn operation.

fh.shut() # Close the file
fh = open("test_append_a.txt") # Open in the default learn mode
print(fh.learn()) # Now, learn and print your entire file

The output is one thing like:

Insert First Line
Append Next Line

Let’s now attempt appending utilizing the “a+” mode. Check out the under code:

# Python Append File in "a+" mode Example
fh = open("test_append_aplus.txt", "a+")
fh.write("Insert First Linen")
fh.write("Append Next Linen") # Set offset place to the beginning
print(fh.learn()) # READ is sucess in a+ mode
 ## Output
 # Insert First Line
 # Append Next Line
fh.write("Append Another Linen") # WRITE one other line to the textual content file # Set the offset for studying
print(fh.learn()) # Do the READ operation once more
 ## Output
 # Insert First Line
 # Append Next Line
 # Append Another Line

Read File in Python

For studying a textual content file, Python bundles the next three features: learn(), readline(), and readlines()

1. learn() – It reads the given no. of bytes (N) as a string. If no worth is given, then it reads the file until the EOF.

''' Python learn() perform '''

2. readline() – It reads the required no. of bytes (N) as a string from a single line in the file. It restricts to at least one line per name even when N is greater than the bytes obtainable in one line.

''' Python readline() perform '''

3. readlines() – It reads each line presents in the textual content file and returns them as an inventory of strings.

''' Python readlines() perform '''

It is really easy to make use of the Python learn file features that you would be able to test your self. Just sort the next code in your IDE or the default Python IDE, i.e., IDLE.

# Python Read File Example
fh = open("sample_log.txt") # No must specify the mode as READ is the default mode
print(fh.learn()) # Expect the entire file to get printed right here # Reset the file offset to the start of the file
print(fh.readline()) # Print simply the primary line from the file # Reset the offset once more
print(fh.readlines()) # Print the listing of traces
fh.shut() # Close the file deal with

Please be aware that the Python search() perform is required to alter the place of file offset. It decides the purpose to learn or write in the file. Whenever you do a learn/write operation, it strikes alongside.

Close File in Python

File handling in Python begins with opening a file and ends with closing it. It implies that it’s essential to shut a file after you might be completed doing the file operations.

Closing a file is a cleanup exercise, which implies to liberate the system sources. It can be important as a result of you’ll be able to solely open a restricted variety of file handles.

Also, please be aware that any try and entry the file after closing would throw an I/O error. You might have already seen us utilizing it in our earlier examples in this publish.

With Statement in Python

If you desire a cleaner and stylish solution to write to a file in Python, then attempt utilizing the WITH assertion. It does the automated clear up of the system sources like file handles.

Also, it supplies out of the field exception dealing with ((*5*)) while you’re working with the information. Check out the next instance to see how with assertion works.

# Write File in Python utilizing WITH assertion
# Sample code(1) Write to a textual content file
fh = open("sample_log.txt", "w") 
   fh.write("I love Python Programming!") 

# Sample code(2) Write utilizing with assertion 
with open("sample_log.txt", "w") as fh: 
   fh.write("I love Python even more!!")

Working pattern code

Below is a full-fledged instance that demonstrates the utilization of the next features:

  • Python Write file utilizing write() & writelines()
  • Python Read file operations utilizing learn(), readline(), and readlines()
# Python Write File/ Read File Example
print("### Python Write File/ Read File Example ###n")
file_handle = open("sample_log.txt", "w") 
list_of_strings = ["Python programming n","Web development n","Agile Scrum n"] 

# Write a newline char at every line in the file
file_handle.write("Welcome! n") 

# Open the textual content file for studying
file_handle = open("sample_log.txt", "r+") 

# Read your entire textual content file and show its content material
print("1) Demonstrate Python read() function")
out = file_handle.learn()
print("n>>>Python read() file output:n".format(out))

# Now, set the file offset to the start

# Read the primary line from the textual content file utilizing readline()
print("2) Demonstrate Python readline() function")
out = file_handle.readline() 
print("n>>>Python readline() file output:ntLine#1".format(out))

# Again, place the file offset to zero 

# Read your entire textual content file utilizing readlines()
print("3) Demonstrate Python readlines() function")
out = file_handle.readlines()
print("n>>>Python readlines() file output:")
for i, line in enumerate(out):
  print("tLine# ".format(i+1, line))

This Python program generates the next output:

read write file in python working example

Attempt the Quiz

We’ve now come to the closure of this Read/Write File in Python tutorial. If you’ve learn it from the begin to finish, then file dealing with can be in your ideas. However, we advocate the next quizzes to try.

These are fast questionnaires to check how a lot information have you ever retained after studying the above stuff.

Also, it’s essential to use these ideas in your tasks or may write some fingers-on code to resolve actual-time issues. It’ll definitely assist you grasp sooner and bear in mind higher.

By the best way, in case you want to be taught Python from scratch to depth, then do learn our step-by-step Python tutorial.

Source hyperlink

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *


You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.