Python .write()
The .write() file method allows the user to add additional text to a file when the file is opened in append mode.
The position of the additional text is determined by the mode the file was accessed in and the stream position. Append mode will insert the text at the current file handle’s reference point. Write mode will first empty the file before inserting the text.
Syntax
file.write(text)
The text is a string that is written to a given file. Then, the length of text is returned.
Example
In the example below, the .write() method is set to append mode ("a") to add text to the end of the gullivers_travels.txt file. The file is then opened to view changes to it:
f = open("gullivers_travels.txt", "a")f.write("Hello Gulliver!!") # Returns 16f.close()f = open("gullivers_travels.txt", "r")print(f.read())f.close() # Always close the file
This will print the following:
Hello Gulliver!!
Codebyte Example
When in write mode ("w"), the .write() method first deletes all of the original text in the gullivers_travels.txt file. Then, it adds text to the file:
All contributors
BrandonDusch- Anonymous contributor
christian.dinh- Anonymous contributor
- Anonymous contributor
- design2461360801
- net1372284738
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours