Python allows you to write data to files using the write() method. Before writing, the file must be opened in write mode (w) or append mode (a).
Write to a File
The write() method writes content to a file.
Syntax
file.write(data)
Example
file = open("sample.txt", "w")
file.write("Hello Python")
file.close()
Read the Written Content
Example
file = open("sample.txt", "r")
print(file.read())
file.close()
Output:
Hello Python
Overwriting Existing Content
When a file is opened in w mode, existing content is removed.
Example
file = open("sample.txt", "w")
file.write("New Content")
file.close()
Write Multiple Lines
Example
file = open("sample.txt", "w")
file.write("Python\n")
file.write("Django\n")
file.write("React")
file.close()
Output
Python
Django
React
Append Data to a File
The a mode adds content to the end of a file without deleting existing content.
Example
file = open("sample.txt", "a")
file.write("\nNode.js")
file.close()
Output
Python
Django
React
Node.js
Using with Statement
The with statement automatically closes the file.
Example
with open("sample.txt", "w") as file:
file.write("Hello World")
Writing User Input to a File
Example
name = input("Enter your name: ")
with open("user.txt", "w") as file:
file.write(name)
Writing a List to a File
Example
languages = ["Python", "Java", "PHP"]
with open("languages.txt", "w") as file:
for language in languages:
file.write(language + "\n")
Output
Python
Java
PHP
Summary
- Use
write()to write data to a file. - The
wmode creates a file and overwrites existing content. - The
amode appends content to the end of a file. - Multiple lines can be written using multiple
write()calls. - The
withstatement automatically closes the file. - Lists and user input can be written to files.
- Always close files when not using the
withstatement.