Working with files is one of the most frequent tasks, irrespective of your problem statement. Whether you are working as a web developer or a data scientist, you need to deal with vast amounts of data daily. Hence, adopting the best practices for file handling might prove to be helpful in the long run. 

Python certainly comes to the rescue here. The Python write to file in-built functions allow you to create, read, write, or append to different types of files. Python provides several in-built functions which would allow you to create, read, write, or append to different types of files. Creating and working with files in GUI is quite easy. However, when it comes to managing and manipulating files in the terminal, you need to get a firm hold of some important commands that would enable you to do so in the most efficient manner.

Before starting with the actual methods in Python to manipulate files, it would be wise to discuss the two types of files that you generally come across.

File Types

In general, Python handles the following two types of files. The first one is a normal text file, and the second one is a binary file consisting of 0s and 1s.

Text Files:

This is the same text file that we generally deal with on a day-to-day basis. An EOL terminates each line in a text file called End-of-line character, which is nothing but the newline (\n) character. This helps when you want to work with only a few specific lines.

Binary files:

Unlike text files, there are no line terminators here. The Python interpreter first converts the 0s and 1s into a machine-understandable language and then stores the data accordingly.

The Ultimate Ticket to Top Data Science Job Roles

Post Graduate Program In Data ScienceExplore Now
The Ultimate Ticket to Top Data Science Job Roles

File Access Modes

File access mode is a critical element of the Python write to file set of functions. It determines how you can use the files once you have opened them. It defines the rights and permissions that you have on the file content. File access modes are very helpful and it allows the interpreter to administer all those operations that a user wants to perform on the file. Moreover, a filehandle in a file is similar to a cursor which tells the file from which location the data has to be read from the file, or written to the file. The file access modes also determine the location of this filehandle. The file access modes you need to learn to master the Python write to file functions are as follows. 

Access Mode

Use

‘x’

It is used to create a new file that is empty.

‘r’

It is used to open the file in read-only mode. Moreover, the file must exist before you use this mode.

‘w’

It is used to open the file in write-only mode. If the file already exists, it is truncated to 0 characters or overwritten by the content that you provide. If it does not exist, then it gets created.

‘a’

It is also used to open the file in write-only mode. If the file already exists, it remains intact, and the content is appended at the end. But if the file does not exist, it gets created.

‘r+’

It is used to open the file for both reading and writing, and the file should exist.

‘w+’

It is also used to open the file for both reading and writing. If it already exists, then it is either truncated or overwritten. If it does not exist, it gets created.

‘a+’

It is also used to open the file for both reading and writing. The only difference is if the file already exists, the content gets appended at the end. If not, then it gets created.

Moreover, you can also specify whether you want to open the file in text or binary mode. The text mode is determined by the letter “t” and the binary mode is determined by the letter “b”. For example, if you want to open a file in read and binary mode, you need to specify “rb”. By default, the file open method uses the text mode to open the file. 

Opening a File

‘Write to file’ in Python can also be done with the help of the open() in-built function in Python, you can easily open files. You don’t need to import any module or package to use the open function in Python. The syntax for the open() function of the python write to file set is -

FileObject = open(r"Name of the File", "Mode of Access")

If you simply mention the name of the file and not the full path, then the file should be in the same directory which contains the Python script you are running. Else, you will need to provide the full path of the file.

Moreover, the letter ‘r’ is used before the file name or path. This is done to prevent the interpreter from reading certain characters as special characters. For instance, if in the file path, you have provided a directory called /temp and you have not included the r character at the beginning, then the interpreter would throw an error suggesting an invalid path. This is so because it will treat \t as a special tab character. The inclusion of the character r converts the path to a raw string. If you are simply writing the file name without the path, then you can opt to ignore the r character.

Check out the below example of the open() function of the python write to file function set for a better understanding.

Let’s suppose you have a text file with the contents below.

PythonWriteToFile_1.

You will be using the same file throughout the tutorial.

Next, consider the code below.

myfile1 = open("simplilearn.txt", "w")

myfile2 = open(r"/home/jarvis/Documents/simplilearn.txt", "r+")

Here, you saw the creation of two file objects for the same file. The first one is directly using the file name. This won’t throw an error because the text file and the Python script are in the same directory. The next one is by providing the file path. You need to use the r character in the beginning so that the interpreter reads the path as raw string.

Closing a File

If the file is no longer required to be accessed or you need to open the file in a different mode, The python write to file function set allows you to simply close the file using the close method. If the file is no longer required to be accessed or you need to open the file in a different mode, you can simply close the file using the close method. It helps in freeing up the memory space that is being eaten up by that file. The syntax of the close() method is - 

FileObject.close()

Considering the same example as above, you can close both files using the below statements.

myfile1 = open("simplilearn.txt", "w")

myfile2 = open(r"/home/jarvis/Documents/simplilearn.txt", "r+")

myfile1.close()

myfile2.close()

Writing to a File

Now we come to the hear fo the this Python write to file tutorial - knowing how to write a file in Python. Python write to file can be done with two in-built methods to write to a file. Python provides two in-built methods to write to a file. These are the write() and writelines() methods.

  • write(): This method is used to insert the input string as a single line into the text file. The syntax is -

    FileObject.write(inputString)
  • writelines(): You can use this method to insert strings from a list of strings into the text file. A common example where it is used is -

FileObject.writelines(inputList) for inputList = [firstString, secondString, ...]

Check out this example to understand it better.

inputList = ["Hello and Welcome to Simplilearn \n", "We have tons of free and paid courses for you\n"]

inputString = "Hello and Welcome\n"

myfile1 = open("simplilearn.txt", "w")

myfile1.write(inputString)

myfile1.close()

print("Using the write method ...")

myfile1 = open("simplilearn.txt", "r")

print(myfile1.read())

myfile1.close(

myfile2 = open("simplilearn.txt", "w")

myfile2.writelines(inputList)

myfile2.close()

print("Using the writelines method ...")

myfile2 = open("simplilearn.txt", "r")

print(myfile2.read())

myfile2.close()

Here, you created a list of strings and a simple string. First, you opened a file object in write mode and used the write method to write the simple string into the file, and then closed it using the close method on the file object. Then, you opened the file object in read mode and printed the contents that you just wrote using the write method, and closed the object again. You did the same for the writelines method next. Check out the output of the program.

PythonWriteToFile_2

Become a Certified Expert in AWS, Azure and GCP

Caltech Cloud Computing BootcampExplore Program
Become a Certified Expert in AWS, Azure and GCP

Appending to a File

Allowing with writing a file in Python, one of the equally common needs is to append files. If you open the file in append mode, the filehandle is automatically positioned at the rear end of the file. Thus, if you write any content, it automatically gets written at the end. Let’s try to append a string in a file.

inputList = ["Hello and Welcome to Simplilearn \n", "We have tons of free and paid courses for you\n"]

inputString = "This is the end\n"

myfile1 = open("simplilearn.txt", "w")

myfile1.writelines(inputList)

myfile1.close()

print("Using the writelines method ...")

myfile2 = open("simplilearn.txt", "r")

print(myfile2.read())

myfile2.close()

myfile3 = open("simplilearn.txt", "a")

myfile3.write(inputString)

myfile3.close()

print("After appending the string...")

myfile4 = open("simplilearn.txt", "r")

print(myfile4.read())

myfile4.close()

Here, you first opened the file in write mode and wrote a few lines using the writelines method. Then, you opened the file in append mode. Instead of clearing the contents of the file and writing from the start, it just appends the new string at the end.

PythonWriteToFile_3

With Statement

You can use the with statement to create a cleaner code when you work with filestreams. It makes the code readable and efficient. When you use a with statement, you don’t need to close the file object. It automatically takes care of the resource allotment and frees up space and resources once you move out of the with block. The general syntax is - 

with open <name_of_file> as  file

Let’s understand this with the help of an example.

inputList = ["Hello and Welcome to Simplilearn \n", "We have tons of free and paid courses for you\n"]

with open("simplilearn.txt", "w") as myfile:

   myfile.writelines(inputList)

with open("simplilearn.txt", "r") as myfile:

   print(myfile.read())

Here, in the first with block, you opened a file in write mode and inserted a few sentences using the writelines method. In the next with block, you opened it in read mode and printed the content. You don’t have to invoke a close method on the file objects as the with statements automatically takes care of it.

PythonWriteToFile_4

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

To sum up, in this ‘Python write to file’ article you’ve covered how to leverage Python built-in methods to write to a file in Python. To sum up, in this article you looked into how to leverage Python built-in methods to write to a file in Python. You explored the different file types, file access modes, and how to open, close, write, and append to a file in Python. Next, you saw how to do the same in a more efficient way using the with statement. 

If you are looking to master the python language and become an expert python developer, Simplilearn’s Python Certification Course is ideal for you. Delivered by world-class instructors, this comprehensive certification course will not only cover the basics of Python, but give you in-depth expertise in key areas such as implementing conditional statements, handling data operations, Django, and shell scripting.

Have any questions for us on this ‘Python write to file’ article? If yes, leave them in the comments section of this article, and our experts will get back to you at the earliest!

Happy Learning!