python logo

Python File Writing


Python hosting: Host, run, and code Python in the cloud!

Python supports writing files by default, meaning no special modules are required. This built-in functionality ensures a smooth experience for developers. One can easily write to a file using the .write() method, which requires a parameter containing the text data.

Before diving into file writing, it’s important to understand the basics:

  • Opening a File: Use the open(filename, 'w') function. Here, filename can be either the actual filename or its path.
  • Writing Data: After opening, you can use the .write() method to input your desired content.
  • Closing a File: Don’t forget to close the file once you’ve finished to ensure data integrity and to free up system resources.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Creating or Overwriting a File in Python

The code below demonstrates how to create a new file or overwrite an existing one:

#!/usr/bin/env python

# Specify the filename
filename = "newfile.txt"

# Open the file with write permissions
myfile = open(filename, 'w')

# Add content to the file
myfile.write('Written with Python\n')

# Ensure the file is closed post operations
myfile.close()

An important note: the ‘w’ flag will cause Python to truncate the file if it already exists. In simpler terms, existing file content will be replaced.

Appending Content to an Existing File

If you wish to retain the existing content and merely add more to a file, the ‘a’ parameter is your go-to:

#!/usr/bin/env python

# Define the filename for appending
filename = "newfile.txt"

# The 'a' flag instructs Python to preserve the file contents and add new content at the end.
myfile = open(filename, 'a')

# Add your desired line
myfile.write('Appended with Python\n')

# Always close the file after operations
myfile.close()

File Modes in Python: A Brief Summary

When working with files, Python offers various modes. Here’s a summary of the essential ones:

📥 Download Python Exercises

🔙 Back | Next ➡️





Leave a Reply:




Copyright © 2015 - 2023 - Pythonspot.  | Cookie policy | Terms of use | Privacy policy
Flag Action
rOpen file for reading
wOpen file for writing (overwrites if exists)
aOpen file for appending (retains existing content)
bBinary mode
r+Open for both reading and writing
a+Read and append
w+Read and write (overwrites if exists)