How to Write a File in Python
Start writing a post
Student Life

How to Write a File in Python


How to Write a File in Python

Whether you use Python to build applications and websites, automate processes, analyze data, or for data visualization, you almost definitely deal with files. Because of this, being able to manage and write files using Python is surely a useful skill that might spare you from the tiresome chore of managing the files manually.

In this blog, we will learn how to operate and handle files in Python along with some practical applications of this expertise.

What is a File

A file is a vital piece of data stored on a computer. Each file's filename and file extension can be used to identify it. They are utilized to use non-volatile memory to retain data permanently.

This information in a file is stored in a certain format and might be as basic as a text file or as complex as a software executable. There are other file types as well, including directory files, data files, binary files, and graphic files, and each of these file types contains a distinct sort of information. All these files are essentially a continuous group of bytes used to store data. Finally, these byte files are converted into binary 1 and 0 for simpler computer processing.

Create a file

The first step before we move ahead is to understand - How to create a file using python on your system? For that, there are two options that python provides. These are:

  1. X mode

Using this create mode with the open() method aids in the creation of a new file. This mode additionally checks to see whether there is an existing file in the system and if so, it will return a 'FileExistsError'.

newFile = open("newfile.txt", "x")

2. W mode

Using this create mode with the open() method you can create a new text file regardless of whether a file with the same name already exists in memory. If it discovers an existing file with an identical name, it does not return an error; instead, it overwrites the existing file.

newFile = open("MyFile.txt", "w")

Python: File Handling

In Python, file operations are carried out in the following order:

1. Open a file: Open a file by using different access modes with respect to the operation you want to perform.

file = open('FileName', 'AccessMode')

Python: Access Modes

Python has six ways or access modes that regulate the kind of activities that can be performed on the opened file. These modes additionally indicate the location of the file handle within the file. A file handle, like a pointer, identifies where data should be read or written to the file. It describes how the file will be utilized once it has been opened. The access mode in python are listed in the table below:

Access Mode


Read Only: r

This mode indicates that the file will only be open for reading.

Read and Write: r+

This mode indicates that the file is available for both reading and writing.

Write Only: w

This mode just allows you to write to the file. Existing files' data is edited and replaced. The handle is at the beginning of the file. If the file doesn't already exist in the folder, it's created.

Write and Read: w+

This mode allows you to read and write to the file.

Append Only: a

In this mode, the file can be opened for writing. Following the previously written data, the newly written data will be added at the end and if the file does not already exist, it is created.

Append and Read: a+

This allows you to read and write to the file. If the file does not exist, it is created. Just like access mode- a, the newly written text will be added at the end.

2. Reading, Writing, and Appending: Once you have opened the file with the right access mode with respect to the kind of operation you want to do on a file, now you can perform various sorts of reading and editing operations on it. There are several functions in Python for reading, writing, and appending files.


For reading a file, it must be opened in 'r' mode. For just reading a file, python has three methods with varied functionality and these are:


The read() function returns the file's content as output. #will open the whole file. #specifying the value of n will display the first n characters till the file is read earlier


To read individual lines from a file, the readline() function can be used.

file.readlines() #this function reads a file until the newline character is reached


The readlines() function always returns a list of all the lines in our file.

file.readlines() #returns a list of the file's remaining lines

Output looks like - [‘line1’, ‘line2’, ‘line3’]


Writing into a file is a handy procedure that is commonly performed after opening a file. When writing into a file, the file is normally opened in write 'w' or append 'a' mode.

file = open('file.txt', 'w')


Once the file is opened in the write mode, use the write() for writing into the file. Using the write() method will write the file's content without inserting any unnecessary characters.



writelines() is another method that you can use if you want to write a list in your file.

list_of_lines = [str1, str2, str3]



There are certain times when you may wish to add to a file or begin writing at the end of an already populated file. This is simple to accomplish by using the 'a' character in the mode argument:

file = open('myfile.txt', 'a')


3. Save or Close the file.

Finally, after opening the file and performing the reading, writing, and appending actions, it is critical to shut it. For this, the close() method is used which shuts the file and frees the memory space used by it. It is used when a file is no longer required or when it is to be opened in a different file mode.

file = open("file.txt", 'r')




Working with files is a must when dealing with huge datasets in machine learning tasks. Because Python is a popular data science language, you should be familiar with the many file operations that Python provides. We hope this blog was helpful in giving you a basic understanding of different file-handling operations in python.

If you want to learn more about python and the various operations associated with it, please feel free to enroll in Board Infinity’s learning path - Python Programming Certification Course where industry experts teach you from the basics and take your growth up to the expertise level.

Report this Content
This article has not been reviewed by Odyssey HQ and solely reflects the ideas and opinions of the creator.

Impact Makers: Melanie Byrd

Find out how this TikTok star gets women excited about science!

Impact Makers: Melanie Byrd

How it all began

Keep Reading... Show less

22 Songs To Use For Your Next GoPro Video

Play one of these songs in the background for the perfect vacation vibes.


We've all seen a Jay Alvarez travel video and wondered two things: How can I live that lifestyle and how does he choose which song to use for his videos?

Keep Reading... Show less

13 Roleplay Plots You Haven't Thought Of Yet

Stuck on ideas for a roleplay? Here you go!

13 Roleplay Plots You Haven't Thought Of Yet

One thing that many creators know is that fun to have characters and different universes to work with but what's the point if you have nothing to do with them? Many people turn to roleplay as a fun way to use characters, whether they're original or from a fandom. It'd a fun escape for many people but what happens when you run out of ideas to do? It's a terrible spot to be in. So here are a few different role play plot ideas.

Keep Reading... Show less

Deep in the Heart of Texas

A Texan's responsibilities when introducing an out-of-stater to Texas culture.


While in college, you are bound to be friends with at least one person who is not from Texas. Now Texas is a culture of its own, and it is up to you to help introduce them to some good ole Texas traditions during their time here. Show your friends that famous Southern hospitality!

Keep Reading... Show less

Marching Through March

Some appreciation for the month of March.


I love the entire year. Well, for the most part. I'm not a big fan of Winter, but even then, every month has something that's pretty great. November? Thanksgiving. December? Winter Holidays. January? New Year's. February? Valentine's and Single Awareness Day. May? Existential dread during finals. But for me, March has always been my favorite month of the year, and for good reason.

Keep Reading... Show less

Subscribe to Our Newsletter

Facebook Comments