Python Write Files

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 Example Read the Written Content Example Output: Overwriting Existing Content When a file is opened […]

2 mins read Lesson 56 of 56 100% through track

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 w mode creates a file and overwrites existing content.
  • The a mode appends content to the end of a file.
  • Multiple lines can be written using multiple write() calls.
  • The with statement automatically closes the file.
  • Lists and user input can be written to files.
  • Always close files when not using the with statement.