- Python Write to File
- Table of contents
- Access Modes for Writing a file
- Writing To An Existing File
- File Write Methods
- with Statement to Write a File
- Appending New Content to an Existing File
- Append and Read on the Same File
- Writing to a Binary File
- Summary
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
Python Write to File
It is pretty standard that large chunks of data need to store in the Files. Python is widely used in data analytics and comes with some inbuilt functions to write data into files.
We can open a file and do different operations on it, such as write new contents into it or modify a file for appending content at the end of a file.
After reading this tutorial, you’ll learn: –
- Writing into both text and binary files
- The different modes for writing a file
- Writing single or multiple lines in a file.
- All methods for writing a file such as write() and writeline() .
- Appending new contents at the end of an existing file
- Open file for both reading and writing.
Table of contents
Access Modes for Writing a file
Access mode specifying the purpose of opening a file.
Whenever we need to write text into a file, we have to open the file in one of the specified access modes. We can open the file basically to read, write or append and sometimes to do multiple operations on a single file.
To write the contents into a file, we have to open the file in write mode. Open a file using the built-in function called open() . This function takes two parameters, namely filename, and access mode, and returns the file pointer.
We can open a file for modifying or overwrite its contents by using any one of the modes described in the following table.
Note: A new file is created in the directory where this Python script is present. Use the absolute path If you want to create and write a file in some other directory.
An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.
For example, E:\PYnative\files_demos\write_demo.txt is an absolute path to discover the write_demo.txt
fp = open(r"E:\demos\files\write_demo.txt", 'w') fp.write('This is new content') fp.close()
Writing To An Existing File
In an already existing file, while opening the file in the write mode, the existing content will be overwritten. The filehandle will be placed at the beginning of the file.
In the below example, we are reading a file to view the old contents. Next, we are opening a file in the write mode to write the new content. We can see that the existing content has been overwritten with the new content.
file_path = r"E:\demos\files\write_demo.txt" fp = open(file_path, 'r') print(fp.read()) fp.close() # overwriting existing content of a file fp = open(file_path, 'w') fp.write("This is overwritten content") fp.close() # Read file fp = open(file_path, 'r') print("Opening file again..") print(fp.read()) fp.close()
This is new content Opening file again.. This is overwritten content
File Write Methods
Python provides two different methods to write into a file. We don’t have to import any module for that.. Below are the methods.
with Statement to Write a File
We can open a file by using the with statement along with open() function. The general syntax is as follows.
with open(__file__, accessmode) as f:
The following are the main advantages of opening a file using ‘with’ statement
- The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
- This also ensures that a file is automatically closed after leaving the block.
- As the file is closed automatically it ensures that all the resources that are tied up with the file are released.
Let us see with an example how we can use this to open a file for writing.
name = "Written using a context manager" with open("Write_demo.txt", "w") as f: f.write(name) # opening the file in read mode to access the file with open("Write_demo.txt", "r") as f: print(f.read())
Written using a context manager
Appending New Content to an Existing File
With the access mode set to a , the open function will place filehandle at the end of the file, and then we can add new text at the end of the existing file using the write() and writelines() functions.
Now let us add some content to the already created ‘Write_demo.txt’ .
name = '\nEmma' address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom'] # append to file with open("Write_demo.txt", "a") as f: f.write(name) f.writelines(address) # opening the file in read mode to access the file with open("Write_demo.txt", "r") as f: print(f.read())
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom
Append and Read on the Same File
In the above example, we have seen how our content got appended to the existing content in the end. We opened the file again to read the contents.
As you can see, we opened a file two times, one for appending and the second call for a reading.
If we try to read without opening the file again we will get the Unsupported operation exception .
name2 = "Antony\n" address2 = ["224 Baker Street\n", "London\n"] with open("Write_demo.txt", "a") as f: f.write(name2) f.writelines(address2) print(f.read())
UnsupportedOperation: not readable
It is possible to do both append and read operations together by using the access mode a+ . where we can open a file and add the content and then read the modified file again. We can perform multiple operations on the same file by using the + sign and the access mode that we wish to perform.
Example: Append and Read
As mentioned above, the write() method moves the filehandle in the append mode at the end. If we try to read the file using the read() method, you’ll get an empty string. Use the seek() method on the file object and move the FileHandle to the beginning.
name = '\nAntony' address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom'] # append to file with open("Write_demo.txt", "a+") as f: f.write(name) f.writelines(address) # move file handle to the start f.seek(0) print(f.read())
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom Antony Address: 221 Baker Street City: London Country:United Kingdom
If you want to perform both write and read then change the access mode to w+. It opens a file for both writings as well as reading. The file pointer will be placed at the beginning of the file. For an existing file, the content will be overwritten.
# Write and Read with open("Write_demo.txt", "w+") as f: f.write('Kelly') # move file handle to the start f.seek(0) print(f.read())
Writing to a Binary File
The open() function, by default, opens a file in text mode. We can read the text file contents using the access mode as r and write new content in the text file using the access mode as w .
To read or write content to a binary file, use the access mode ‘B’. For writing, it will be wb , and for reading, it will be rb .
The open() function will check if the file already exists and if not, will create one. In the existing file, all the content will be deleted, and new content will be added.
file = open("Writedemo.bin", "wb") file.write("This is a sample string stored in binary format") file.close()
The above code will create a binary file and the write the string passed in the write() method.
Summary
In this article we have covered the basic methods for modifying a file. We also saw in detail the different access modes for performing the write operations. In addition to this we saw the different access modes for appending new content at the end of the file.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ