- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS.Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Object & Classes
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Questions & Answers
- Python - Online Quiz
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python File write() Method
The Python File write() method writes a string to a file. When the method writes the string into this file, it is first written into the internal buffer; and once this buffer is full, the contents are then transferred to the current file. Due to this buffering, the string may not actually show up in the file until the flush() or close() methods are called.
If the current is empty, the method adds content to it from the beginning; but if it already contains some text, the position at which this text is added into the file depends on the position of the file pointer; and this position varies based on the file modes. Various scenarios are as follows −
- If the file is opened in the writing modes (w or w+), the existing text is erased from the file and the file pointer moves to the beginning of the file. Therefore, the write() method writes from the beginning in this case.
- If the file is opened in the append modes (a or a+), the existing text remains as it is and the file pointer remains at the end of file. Hence, the new text is added after the existing contents.
- If the file is opened in the read and write mode (r+), the pointer moves to the beginning of the file and replaces the existing content in the file. However, the entire text is not replaced; instead the write() method only replaces the characters in the existing strings with the characters in the corresponding indices of the new string.
- This method is not effective if the file is opened in the reading mode (r).
Syntax
Following is the syntax for the Python File write() method −
fileObject.write(str)
Parameters
str − This is the String to be written in the file.
Return Value
This method does not return any value.
Example
Consider a demo file "foo.txt" containing strings.
This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line
The following example shows the usage of the Python File write() method. The demo file is opened in the write (w) mode, so the existing content in the file will be erased and new content is inserted using this method. And since this method returns no values, the file must be directly checked to see the reflected changes.
# Open a file in write mode fo = open("foo.txt", "w") print("Name of the file: ", fo.name) # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line # Write a new line into the file str = "This is the new line" line = fo.write( str ) print("Check the file to see the reflected changes") # Close opened file fo.close()
When we run above program, it produces following result −
Name of the file: foo.txt Check the file to see the reflected changes
Example
In the example above, one has to open the file to check whether the changes are reflected or not. But we can also try to display the file contents in the terminal itself. To do that, once the file is rewritten using the write() method, we close the file. Then, this file is opened again in the read (r) mode, and file contents are read using the read() method.
# Open a file in write mode fo = open("foo.txt", "w") print("Name of the file: ", fo.name) # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line # Write a new line fo.write("This is the new line") # Close opened file fo.close() # Open the file again in read mode fo = open("foo.txt", "r") line = fo.read() print("File Contents:", line) # Close opened file again fo.close()
On executing the program above, the output is displayed on the terminal as follows −
Name of the file: foo.txt File Contents: This is the new line
Example
If we try to open a file that does not exist in the directory with the write (w) mode, a new file is created with the given name. In the following example write() method is called on this file and new contents are inserted into it.
# Open a non-existent file in write mode fo = open("new.txt", "w") print("Name of the file: ", fo.name) fo.write("This is the new line") print("Check the file to see the reflected changes") # Close opened file fo.close()
Let us compile and run the given program, the output is displayed as follows −
Name of the file: new.txt Check the file to see the reflected changes
Example
The write() method can also be used when the file is opened in the append (a or a+) mode.
In this example, a file named "foo.txt" is opened in the append mode "a". Usually, we will use the seek() method to move the file pointer to the end if we want append content into the file, but it is not necessary here. Since the file is opened in append mode, the write() method writes content at the end of file. The file contents are displayed in the terminal itself.
# Let the test file contain the following strings # Hello! # This is Tutorialspoint # Welcome # Open the test file in append mode fo = open("test.txt", "a") print("Name of the file: ", fo.name) line = fo.write("This is the new line") # Close opened file fo.close() # Open the file again in read mode fo = open("test.txt", "r") line = fo.read() print("File Contents:", line) # Close opened file again fo.close()
Once the program is compiled and run, the output is displayed in the terminal as follows −
Name of the file: test.txt File Contents: Hello! This is Tutorialspoint WelcomeThis is the new line
Example
If we use the write() method on a file opened using the read and write mode (r+), the pointer moves to the beginning of the file and replaces the existing content in the file.
In the example below, we are opening an existing file "foo.txt" in the "r+" mode. The write() method replaces the character of the existing strings from the beginning of the file with the corresponding indices of the new string argument passed to it.
# Open the test file in append mode fo = open("foo.txt", "r+") print("Name of the file: ", fo.name) fo.write("This is a new line") print("Check the file to see the reflected changes") # Close opened file again fo.close() # Open the file again in read mode fo = open("foo.txt", "r") line = fo.read() print("File Contents:", line) # Close opened file again fo.close()
Let us compile and run the program above, to produce the result as follows −
Name of the file: foo.txt File Contents: This is a new lineThis is 2nd line This is 3rd line This is 4th line This is 5th line
To Continue Learning Please Login
Login with Google